【发布时间】:2012-02-12 05:24:27
【问题描述】:
在我看来派生类不继承基类赋值运算符
如果派生类继承基类赋值运算符,你能解释一下下面的例子吗
在下面的代码中,我在 Derived 中重写了基类 operator=,以便 Derived 类默认赋值运算符调用重载的 operator=
#include <iostream>
using namespace std;
class Base
{
public:
Base(int lx = 0):x(lx)
{
}
virtual Base& operator=( const Base &rhs)
{
cout << "calling Assignment operator in Base" << endl;
return *this;
}
private:
int x;
};
class Derived : public Base
{
public:
Derived(int lx, int ly): Base(lx),y(ly)
{
}
Base& operator=(const Base &rhs)
{
cout << "Assignment operator in Derived"<< endl;
return *this;
}
private:
int y;
};
int main()
{
Derived d1(10,20);
Derived d2(30,40);
d1 = d2;
}
它给出了输出
在 Base 中调用赋值运算符
我已经将基类 operator= 重写为派生类,所以如果派生类继承基类 operator= 那么它应该被 operator= 覆盖(我已经写在派生类中),现在派生类默认运算符= 应该调用被覆盖的版本,而不是来自基类 operator=。
【问题讨论】:
标签: c++ inheritance assignment-operator