1
考虑下面的代码:C++赋值运算解决
struct A
{
void foo(const char *) { cout << __PRETTY_FUNCTION__ << endl; }
A & operator = (const A & ) { cout << __PRETTY_FUNCTION__ << endl; return * this; }
};
struct B : public A
{
void foo(const char *) { cout << __PRETTY_FUNCTION__ << endl; }
A & operator = (const A & other) { cout << __PRETTY_FUNCTION__ << endl; return * this; }
};
那么当我们调用这个成员:
B b;
b.foo("hehe");
b = b;
会打印:
void B::foo(const char *)
A& A::operator=(const A&)
问:为什么B :: foo隐藏A :: foo,但B :: operator =不?
好的,据我所知,编译器会生成对于B以下代码: B&运算符=(常数B&B) { A ::运算符=(B); return * this; } 但是如果我们有虚拟的“A :: operator =”,那么应该调用“B :: operator =”,因为它覆盖了“A :: operator =”。 但事实并非如此。 – drinian 2010-12-06 14:00:58