我想了解這種行爲,但似乎我沒有。請參閱此代碼:派生類是否間接繼承了基的賦值運算符?
#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