#include <iostream>
using namespace std;
class C {
public:
C() : v(0) {}
int operator=(const int &rhs) { return v = rhs; }
// int operator+=(const int &rhs) { return v += rhs; } ←=以外は問題ない
int v;
};
struct D : public C {
};
int main()
{
D d;
cout << d.v << endl;
d = 10;
cout << d.v << endl;
}
これが通らない。例えばVC++2010だと、
test.cpp(19) : error C2679: 二項演算子 '=' : 型 'int' の右オペランドを扱う演算子が見つかりません (または変換できません)。 test.cpp(13): 'D &D::operator =(const D &)' の可能性があります。 引数リスト '(D, int)' を一致させようとしているとき
……という感じのコンパイルエラーが発生する。
Dクラスを以下のようにすれば問題ない。
struct D : public C {
using C::operator=; // ←これが要る
// int operator=(const int &rhs) { return C::operator=(rhs); } // ←或いはこれ
};
OK、継承されないという事も回避策も分かった。だが何故継承されないという仕様になっているのだろう?
ラベル:C++

