C++在子类中创建一个可用的方法

C++ create a usable method in the child class

本文关键字:一个 方法 子类 创建 C++      更新时间:2023-10-16

这是我的基类

class Base {
protected:
    int number;
public:
    Base(int num);
    virtual void display() = 0;  
};

这两个类继承了Base。

class Derived: public Base {
public:
    Derived(int num);
    void display(){cout <<"hello";}
    void other();
};
class Derived2: public Base {
public:
    Derived(int num);
    void display(){cout <<"hello other";}
};

这个类允许我实例化我的两个类Derived和Derived2

class Foo{
private:
    Base * toto[2];
public:
    Foo(){
     toto[0] = new Derived;
     toto[1] = new Derived2;
    }
    void doSomething();
}

我想做这个

void Foo::doSomething(){
    toto[0]->other();
}

$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$

最后一个问题我创建一个继承了Derived2Base 的新类

class Derived3: public Derived2, public Base {
public:
    Derived(int num);
    void display(){cout <<"hello";}
    void other();
};

现在我想做这个

toto[0] = new Derived3
This my error message 

从派生类"Derived3"到基类"base"的转换不明确:classDerived3->classBaseclass Derived3->class Derived2->class Base

从不兼容的类型"Derived3*"分配到"Base*"

如果toto[0]总是指向Derived,而toto[1]总是指向Derived2,那么您可能应该这样做:

class Foo{
private:
    Derived d1;
    Derived2 d2;
    Base * toto[2];
public:
    Foo(){
        toto[0] = &d1;
        toto[1] = &d2;
    }
    void doSomething() {
        d1.other();
    }
};

如果您确实有真正的需要创建一种无法静态检查键入的情况,那么请使用dynamic_cast。但如果可能的话,尽量避免这种情况。不要把C++当作一种动态类型语言。

Derived* dptr = dynamic_cast<Derived*>(toto[0]);
if (dptr) {
    dptr->other();
} else {
    throw std::logic_error("toto[0] should point to Derived");
}

您可以使用Dinamic cast:http://en.cppreference.com/w/cpp/language/dynamic_cast

void Foo::doSomething(){
    Derived* e =  dynamic_cast<Derived*>(toto[0]);
    if (e != nullptr) //Did cast work?
        e->other();
}