【发布时间】:2012-02-10 15:41:40
【问题描述】:
我试图理解这种行为,但似乎没有。请看这段代码:
#include <iostream>
using namespace std;
class Base
{
public:
void operator=(const Base& rf)
{
cout << "base operator=" << endl;
this->y = rf.y;
}
int y;
Base() : y(100) { }
};
class Derived : public Base
{
public:
int x;
Derived() : x(100) { }
};
int main()
{
Derived test;
Derived test2;
test2.x = 0;
test2.y = 0;
test.operator=(test2); // operator auto-generated for derived class but...
cout << test.x << endl << test.y << endl;
cin.ignore();
return 0;
}
程序输出:
> base operator=
> 0
> 0
现在我感到困惑的是:
该规则规定派生类从不继承赋值运算符,而是创建自己的operator=,但在此示例中,基类的operator= 会在派生类上调用。
其次,我能够在派生类上显式调用赋值运算符,而派生类中并未显式定义该赋值运算符。
现在,如果我理解正确,这意味着任何用户定义的基运算符总是在派生类上被调用?
【问题讨论】:
标签: c++ inheritance assignment-operator