gpt4 book ai didi

C++赋值运算符解析

转载 作者:太空宇宙 更新时间:2023-11-03 10:35:39 25 4
gpt4 key购买 nike

考虑以下代码:

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,因此编译器为您创建了一个。编译器创建的是调用A的赋值运算符。

因此,如果您的问题是“问题:为什么 B::foo 隐藏了 A::foo,而 B::operator= 却没有?”应该读作“How is operator= difference from an ordinary function”,区别是如果你不自己写,编译器会为你提供一个。

关于C++赋值运算符解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4366863/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com