我有以下情况
class B {
public:
B() {};
virtual ~B() {};
virtual void seti( int x ) { i = x; };
virtual void setj( int x ) { j = x; };
virtual void add() =0;
protected:
int i;
int j;
};
class D : public B {
public:
virtual void add() { cout << "D-add:" << i + j << endl; };
};
class E: public B {
public:
void seti( int x ) { i = x; };
void add() { cout << "E-add:" << i + j << endl; };
void mult() { cout << "E-mult:" << i * j << endl; };
};
int _tmain(int argc, _TCHAR* argv[])
{
D *d = new D();
d->seti(4); d->setj(5); d->add();
E*e = d;
e->seti(8); e->add(); e->mult();
return 0;
}
I get the following error 1>.\CallBack.cpp(38) : error C2440: 'initializing' : cannot convert from 'D *' to 'E *' 1> Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-styl`enter code here`e cast
我想做的是当我实例化 E 时,我使用了 D 的所有信息/成员,并用它做更多的事情。我应该像上面那样使用分层继承还是应该使用多级继承或者是否有其他更好的方法。请指教。谢谢!
最佳答案
你可以改变
class E: public B {
到
class E: public D {
关于c++ - 同一基类的两个派生对象如何通信?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10920120/