1 c++ assignment-operator member-hiding
请考虑以下代码:
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; }
};
Run Code Online (Sandbox Code Playgroud)
然后我们称这个成员为:
B b;
b.foo( "hehe" );
b = b;
Run Code Online (Sandbox Code Playgroud)
将被打印:
void B::foo( const char *)
A& A::operator=(const A&)
Run Code Online (Sandbox Code Playgroud)
问题:为什么B :: foo隐藏A :: foo,但B :: operator =不隐藏?
你所看到的根本不是一个隐藏的问题.您没有创建赋值运算符以将B分配给B,因此编译器为您创建了一个.编译器创建的那个是调用A的赋值运算符.
因此,如果您的问题"问题:为什么B :: foo隐藏A :: foo,但B :: operator =不隐藏?" 应该读作"运算符如何=与普通函数不同",区别在于如果你不编写自己的函数,编译器将为你提供一个.
| 归档时间: |
|
| 查看次数: |
256 次 |
| 最近记录: |