【问题标题】:Is it possible to have one instance for all child classes?是否可以为所有子类创建一个实例?
【发布时间】:2019-09-17 07:33:37
【问题描述】:

我有一个父类和几个子类。 我想要一个父实例并根据特定的 ID 对其进行实例化。 子类可能具有父类中没有的函数,而我似乎无法访问它们。

class ParentInterface {
public:

   int gettemp();
};

class child1: public ParentInterface{
public:
    child1();
    virtual ~child1();
    int gettemp();  
    int getrand();

 };  

class child2: public ParentInterface{ 
public:
    child2();
    virtual ~child2();
    int gettemp();  

};

主要我想如下使用:

int main(int argc, char** argv) {

    int id = 1;
    ParentInterface *c;

    if(id == 1) c = new child1();

    if(id == 2) c = new child2();

    cout << "print temp: " << c->gettemp() << endl;

    cout << "print rand: " << c->getrand() << endl;

}

我无法从第一个孩子访问 getrand() 函数。我知道 c 被声明为父类,但是有没有办法解决这个问题而不必将 getrand() 函数添加到父类?

【问题讨论】:

    标签: c++ c++98


    【解决方案1】:

    您需要使用dynamic_castc 转换为真实的child1

    例如:

    dynamic_cast<child1*>(c)->getrand();
    

    如果不能保证是child1,则需要检查dynamic_cast是否成功:

    child1 * child = dynamic_cast<child1*>(c);
    if(child != nullptr) // if it succeeded
    {
        child->getrand();
    }
    

    但正如 @VTT 所注意到的,您的父类不是多态的。要使其工作,您必须在父类中将gettemp() 声明为virtual
    这将使您的父类具有多态性,因此,当您在实际上是子类的父类上调用此方法时,将改为调用子方法。


    编辑:

    顺便说一句,您的程序正在泄漏内存。你总是必须释放你动态分配的内存(new --> delete / new [] --> delete [])。
    此外,您的main() 函数应该返回一个int(如果它正常结束,通常为零)。

    【讨论】:

    • dynamic_cast 不应该也不能在这里使用(因为父类不是多态的)。
    • @VTT 哦,对了,我没有仔细阅读代码,我会在我的答案中添加通知。
    • 如果你知道实际的类型是什么,你应该使用static_cast,以节省dynamic_cast的开销。注意!如果您的对象的实际类型不是您所期望的,那么静态转换不会失败,并且您最终会出现未定义的行为
    • @Fareanor 是的,我知道我应该为 main 添加 delete 并返回 0,这只是我的代码的一个小例子。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-29
    • 1970-01-01
    • 1970-01-01
    • 2013-06-13
    • 2020-04-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多