2017-10-04 12 views
0

C++完全リファレンスには、「=演算子を除いて、演算子関数は派生クラスに継承されています。オーバーロードされた代入演算子の継承

しかし、私は次のコードの動作を理解cannt:

#include<iostream> 
using namespace std; 
int main(){ 

    class b{ 
     int i; 
     public: 
      int operator=(b parm){ 
       cout<<"base overload"; 
      }; 
    }; 
    class d: public b{ 
     int j; 
     public: 
    }; 



    b inst1,inst11; 
    d inst2,inst22; 
    int a; 

    inst1=inst11; //works because assignment operator is overloaded for b 

    inst2=inst22; //If =operator function is not inherited then why does it output "base oberload" 

    inst1=inst2; //works because assignment overloaded for b 

// inst2=inst11;  //But if b was inherited then this should also work but it doesnt 


} 

私は2つの出力文「ベースのオーバーロード」を期待していますが、それは3なぜを出力しています?これはナットを運転しています

答えて

0

operator=は継承されません。しかし、コンパイラはdoperator=generate implicitlyを返します。これは、ベースサブオブジェクトの割り当てにb::operator=を呼び出します。

オペレータは、スカラーの組み込み割り当てとクラスタイプのコピー代入演算子を使用して、オブジェクトの基底と非静的メンバーの初期化順序でメンバワイズコピーを代入します。

その後、

inst2=inst22; //If =operator function is not inherited then why does it output "base oberload" 

生成d::operator=がここに呼ばれています。その内部にはb::operator=が呼び出されます。

b::operator=

inst1=inst2; //works because assignment overloaded for b 

はそれが引数として bを期待して inst2は暗黙的に基底クラス bに変換することができ、ここに呼ばれています。

// inst2=inst11;  //But if b was inherited then this should also work but it doesnt 

d::operator=引数が、inst11が暗黙的に派生クラスdに変換することはできませんと、それはdを期待し、ここで呼ばれるように試みられています。

関連する問題