c++ - 使用抽象指针调用派生类函数

标签 c++ abstract-class

我是第一次使用纯虚函数和接口(interface),但遇到了一些麻烦,可能是因为我没有完全理解一些基础知识。

在 main 函数中,我试图创建一个派生类的对象“a”,它在类中创建另一个对象“obj”并将 obj 的成员变量设置为某个值。 后面在main函数中,想打印obj的成员变量。

错误类“AbstractB”没有成员“setVar”出现在 DerivedA.h 中。 setVar 函数不是抽象类的一部分,因为在不同的派生类中,var 可能具有不同的数据类型。

抽象A.h

class AbstractA
{
public:
    AbstractA() {}
    virtual ~AbstractA() {}

    virtual void buildObj() = 0;
    AbstractB* getObj() { return obj; }

protected:
    AbstractB* obj;
};

摘要B.h

class AbstractB
{
public:
    AbstractB() {}
    virtual ~AbstractB() {}

    virtual void doSthWithVar() = 0;

    // All derived classes have a private member variable var of varying data types
};

DerivedA.h

 class DerivedA: public AbstractA
 {
 public:
    // buildObj() creates some numbers e.g. 1
    void buildObj() { obj->setVar( 1 ); } // Error due to calling the function using the abstract class instead of the derived one
 };

DerivedB.h

class DerivedB
{
public:
    void setVar( int i ) { var = i; }
    void doSthWithVar(){ std::cout << var << std::endl; }

private:
    int var;
};

主要.cpp

int main()
{
    DerivedA a;
    a.buildObj(); // Creating a DerivedB object which is holding a variable var

    // I want to do something like this
    AbstractB* obj = a.getObj();
    obj->doSthWithVar(); // Should print 1
}

有没有什么方法可以调用 DerivedA.h 中的 setVar() 函数以允许以后在不干扰抽象类结构的情况下检索 var?

编辑:

我通过以下方式实现了 Robert Andrzejuk 的解决方案:

class DerivedA: public AbstractA
{
public:
    void buildObj() 
    { 
        DerivedB* b = new DerivedB();
        b->setVar( 1 );
        obj = b;
    }
};

最佳答案

我没看到您在哪里创建了 DerivedB 的实例?

最符合逻辑的地方看起来像DerivedA。 这就是您拥有调用所需函数的所有信息的地方。

class DerivedA: public AbstractA
{
   DerivedB b;
public:
   // buildObj() creates some numbers e.g. 1
   void buildObj() 
   { 
        b.setVar( 1 );
        obj = &b; 
   }
};

关于c++ - 使用抽象指针调用派生类函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48142849/

相关文章:

c++ - 为什么我的程序在输入矩阵值时崩溃?

c++ - 与 float 和 float 文字相比的奇怪输出

C++ 是否为某些通用读和/或写访问分离了抽象类(接口(interface))?

c# - 运算符重载多态返回泛型集合

c++ - 您可以在 C++ 中缓存虚函数查找吗?

c++ - 为什么我不能打印工资?

c++ - 为什么在另一个案例中允许在 block 内使用 case 语句?

c++ - 对函数 AST 声明的抽象格式的混淆

c# - 抽象,还是不抽象

oop - 使用抽象父类(super class)的好的设计模式是什么?