8

我有一个基类和两个派生类,我需要将指向派生类对象的指针复制到另一个类中的一个,例如示例。

class Base
{
public:
    Base(const Base& other);
}

class Derived1 :public Base
{
public:
    Derived1(const Derived& other): Base(other){...};
}

class Derived2: public Base
{
public:
    Derived2(const Derived& other): Base(other){...};
}

main()
{
    Derived 1 d1;
    Derived2 d2(d1)
}

我尝试从 Derived 1 ti base (允许向上转换)传递,然后将 *dynamic_cast* Base 传递给 Derived2 并调用复制构造函数,但它不起作用。我只需要在两个派生对象之间复制两个对象的 Base 部分。

4

1 回答 1

5

如果您的意图只是复制基类部分,请创建一个接收基类的构造函数。

Derived2(const Base& other): Base(other){...};

Derived1(const Base& other): Base(other){...};
于 2012-12-19T10:01:28.847 回答