我有一个基类和两个派生类,我需要将一个指向派生类对象的指针复制到另一个类中,就像示例一样。
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部分。
答案 0 :(得分:5)
如果您的目的是复制Base类部分,请创建一个接收基类的构造函数。
Derived2(const Base& other): Base(other){...};
Derived1(const Base& other): Base(other){...};