c++ - 同一基类的两个派生对象如何通信?

标签 c++ design-patterns derived-class

我有以下情况

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/

相关文章:

C#:如何在基类的构造函数中使用派生类的 const 变量

c++ - ELF文件中的虚拟表存放在哪个段,数据段还是其他?

c++ - new/delete/free store 和 malloc/free/heap 组合

c++: BOOST_ASIO 服务器回复不符合预期?

angular - 带有 Angular 和 Typescript 的策略模式

c# - 什么是实现缓存备用模式的好方法?

c++ - 如何停止类的重新定义

php - 尝试在 php 中实现(理解)Decorator 模式

java - 使用 Java 派生类数组时出错

c++ - 如何实现一个继承自fstream的类