给定一个指向抽象基类A*
的指针,我想复制或分配它(作为基类)并调用派生的复制构造函数或赋值运算符。我理解复制构造函数不能是虚拟的,所以复制构造函数可能不是这样做的选项,但是赋值运算符是。不过,它似乎不起作用:以下代码打印
assigned a
x!
destroyed b
destroyed b
未能分配b。
#include <iostream>
using namespace std;
class A
{
public:
virtual void x()=0;
virtual ~A() {}
virtual A& operator=(const A& other) { cout << "assigned a" << endl; return *this;}
};
class B : public A
{
public:
virtual B& operator=(const B& other) { cout << "assigned b" << endl; return *this;}
virtual void x() { cout << "x!" << endl; }
virtual ~B() { cout << "destroyed b" << endl; }
};
int main()
{
A* a = new B();
A* aa = new B();
*aa=*a;
aa->x();
delete a;
delete aa;
return 0;
}
怎么做?
编辑下面已经正确回答了这个问题,但这是一个错误的问题。我不应该尝试覆盖赋值运算符,因为我不希望A的子类将分配给另一个。对于更简单的答案(希望如此),请参阅C++ elegantly clone derived class by calling base class
答案 0 :(得分:4)
问题是,B::operator=
不会覆盖 A
中的那个。将其更改为
virtual A& operator=(const A& other) { cout << "assigned b" << endl; return *this;}
它会起作用。另外,在覆盖成员函数时尝试使用here关键字(需要C ++ 11)。如果您不覆盖,代码将无法编译。在你的情况下,它会抓住你的错误
PS:你可能在考虑错误:&#39;虚拟B&amp; B :: operator =(const B&amp;)&#39;标记为&#39;覆盖&#39;,但不覆盖
override
。为了使它起作用,除了返回类型之外,函数的签名必须相同。例如,这将起作用:
virtual B& operator=(const A& other) { cout << "assigned b" << endl; return *this;}