从派生类中调用运算符 =

发布于 2024-11-02 20:39:30 字数 467 浏览 1 评论 0原文

这是来自《Effective C++ 第二版 scott meyers》(第 70 页)第 16 项,

作者在没有太多解释的情况下写道,当按以下方式调用基类运算符 = 时

Base::operator=(rhs);

,如果 operator = ,某些编译器(尽管不正确)会拒绝此操作 是由编译器生成的(参见第 45 项),因此更好地使用

static_cast<base&>(*this) = rhs;

第 45 项,他提到如果基类 operator = 是私有的,则派生类= 无权调用它。

但在最初的问题中,编译器拒绝它,因为它是由编译器生成的(必须是公开的),

对此的任何帮助(链接)都会有所帮助。 (很难用谷歌搜索这些类型的问题)

This is from the item 16 of effective C++ 2nd edition scott meyers (page 70)

Author writes without much explanation that when base class operator = is called in the following fashion

Base::operator=(rhs);

some compiler (though incorrectly) reject this, if the operator = was generated by compiler(see item 45) so better use

static_cast<base&>(*this) = rhs;

in item 45 he mentions that if base class operator = is private, derived class = has no right to call it.

but in original question compiler was rejecting it because it was generated by compiler (which has to be public)

any help (link) on this would be helpful. (its very difficult to google these types of questions)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

九公里浅绿 2024-11-09 20:39:30

但是在最初的问题中编译器是
拒绝它,因为它是生成的
由编译器(必须是公开的)

也许我明白你想要什么。

编译器生成的赋值运算符成为公共的。但第 16 项与访问级别无关。此 static_cast(*this) 是针对损坏的编译器的解决方法。在第 16 项中,Scott Meyers 表示,当编译器生成基类赋值运算符时,可能需要解决方法。顺便说一句,自第二版发布以来发生了很多变化。第三版不再提及解决方法。

关于私人赋值运算符。 Item 45 表示,如果基类赋值运算符被设为私有,则编译器无法为派生类生成赋值运算符,因为编译器生成的赋值运算符依赖于基类赋值运算符。在这种情况下,您必须手动为派生类编写赋值运算符,或者让派生类不带有赋值运算符。

but in original question compiler was
rejecting it because it was generated
by compiler (which has to be public)

Maybe I understand what you want.

Compiler generated assignment operator becomes public. But item 16 isn't about access level. This static_cast<base&>(*this) is a workaround for broken compilers. In item 16 Scott Meyers says that the workaround might be needed when the base class assignment operator is generated by the compiler. Btw, a lot changed since the 2nd edition was out. 3rd edition doesn't mention the workaround any more.

Regarding private assignment operators. Item 45 says that if base class assignment operator was made private, then the compiler can't generate assignment operator for the derived class, because compiler generated assignment operator relies on base class assignment operator. In that case you would have to manually write the assignment operator for the derived class or leave the derived class without an assignment operator.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文