我有以下的情況兩個相同基類的派生對象如何通信?
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的信息/會員,並做一些事情更與它。我應該像上面那樣使用分層繼承,還是應該使用多級繼承,還是有其他更好的方法。請指教。謝謝 !
'E'不是來自'D' –
像靜態成員? http://stackoverflow.com/questions/1390913/are-static-variables-in-a-base-class-shared-by-all-derived-classes – corn3lius