我想了解这种行为,但似乎我没有。请参阅此代码:派生类是否间接继承了基的赋值运算符?
#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
现在在那里我感到困惑的是: 规则说,一个派生类中从未继承分配新建分配FY操作,而是创建了自己的operator=
然而在这个例子中,基类的operator=
被派生类调用。
其次,我能够明确地调用分配新建分配FY运营商在派生类中,这是不是又在派生类中明确定义。
现在,如果我理解正确的话,这意味着任何用户定义的基本的操作总是被在派生类中调用?
这是否意味着用户定义的运算符不会调用子对象的运算符?你是说只有编译器生成的操作符调用的子对象的操作符? – codekiddy 2012-01-15 04:18:18
@codekiddy:除非你自己调用基类版本,否则编译器不会为你做。 – Xeo 2012-01-15 04:19:06
非常感谢你! – codekiddy 2012-01-15 13:03:28