C++在子类中创建一个可用的方法
C++ create a usable method in the child class
这是我的基类
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();
}
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
最后一个问题我创建一个继承了Derived2
和Base
的新类
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();
}
相关文章:
- 不能将方法返回的值用于另一个方法
- C++有没有办法强制重写一组方法,如果其中一个方法在子类中具有重写?
- 我在C++中编写了一个方法来打印树类的预序,但它显示了分割错误
- 重写另一个方法 [C++] 使用的超类回调函数
- C++:如何使用传递引用在一个方法中返回多个值
- 为什么一个方法对同一个变量有常量和非常量参数?
- 从同一类中的另一个方法调用方法时出错
- 向现有类添加一个方法以逐行读取文件的内容
- 无法从派生的一个方法调用基类方法
- 如何将一个方法中的值返回到同一类的另一个方法
- 方法重载 C++ -> 只有一个方法调用
- 在另一个线程中执行一个方法
- 是否可以在另一个方法中使用模板类中定义的虚拟方法
- 调用方法,该方法修改字段,而使用该字段的另一个方法正在执行
- 将一个方法作为参数传递给另一个方法,该方法本身将传递的方法传递给 std 线程
- 仅专用于模板类的一个方法(部分)
- 确定一个方法是否是纯虚拟的(c++)
- 是否可以判断一个方法在编译时是否可以公开访问
- 我正在尝试创建一个方法,该方法使用指针算术返回一对,它是否会出错
- 从 ndk 中的 jni 方法调用另一个C++方法