问题描述
在我看来,Derived类不继承基类赋值运算符
如果Derived类继承Base类赋值运算符,请解释下面的示例
It seems to me that Derived class don't inherit base class Assignment operator
if Derived class inherit Base class assignment operator , can you please explain the following example
在下面的代码中我覆盖了基类operator =在Derived中,所以Derived类默认赋值操作符调用重载operator =
In the following code I am overriding base class operator= in Derived, so that Derived class default assignment operator calls overloaded 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;
}
它提供输出
我已将基类operator =重写为派生类,所以如果派生类继承基类operator =,那么它应该被operator =(我已经写在派生类中)覆盖,现在Derived类default operator =应该调用覆盖版本,而不是从基类operator =。
I have re-written base class operator= into derived class, so if derived class inherits base class operator= then it should be get overridden by operator= (that i have written in derived class), and now Derived class default operator= should call overridden version and not from the base class operator=.
推荐答案
编译器为Derived生成一个默认赋值运算符但是,默认赋值运算符会调用类的成员和基类的所有赋值运算符。
The compiler generates a default assignment operator for Derived (which hides the operator of Base). However, the default assignment operator calls all assignment operators of the class' members and base classes.
这篇关于派生类继承基类的赋值运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!