可以 C++赋值运算符是自由函数吗?

发布于 2024-09-06 19:39:50 字数 256 浏览 10 评论 0原文

我正在尝试这样的事情:

Foo & operator=(Foo & to, const Bar &from);

但我收到此错误:

E2239 'operator =(Foo &, const Bar &)' must be a member function

哪些运算符可以/不能定义为自由函数是否有限制,如果有,为什么?

I'm trying something like this:

Foo & operator=(Foo & to, const Bar &from);

But I'm getting this error:

E2239 'operator =(Foo &, const Bar &)' must be a member function

Are there limitations on which operators can/cannot be defined as Free Functions, and if so, why?

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

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

发布评论

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

评论(2

魂ガ小子 2024-09-13 19:39:50

赋值运算符必须是非静态成员函数,并且必须只有一个参数:

赋值运算符应由只有一个参数的非静态成员函数来实现 (C++03 13.5.3/1)。

operator()operator[]operator-> 也必须实现为非静态成员函数。

特定于类的operator newoperator delete(及其变体)必须实现为静态成员函数(请注意,它们是隐式静态的,即使它们没有使用static 关键字)。

The assignment operator must be a non-static member function and must have exactly one parameter:

An assignment operator shall be implemented by a non-static member function with exactly one parameter (C++03 13.5.3/1).

operator(), operator[], and operator-> must also be implemented as non-static member functions.

Class-specific operator new and operator delete (and variants thereof) must be implemented as static member functions (note that these are implicitly static, even if they are not declared with the static keyword).

难如初 2024-09-13 19:39:50

它不能。

我猜原因与复制构造函数有关。它们具有非常相似的语义,并且您不能像其他构造函数一样在类外部定义复制构造函数。所以,他们不想把双胞胎分开太远(以避免双胞胎悖论:)。

PS C++ 中的一个遗憾是您无法向现有类添加成员。这没有低级的原因。如果可能的话,您可以通过不在类定义标头中声明私有函数来解耦标头和 cpp 依赖关系。

It cannot.

The reason, I guess, has to do with copy constructor. They have very similar semantics, and, you cannot define a copy constructor outside of a class just like other constructor. So, they didn't want to separate the twins far apart (to avoid the twins paradox:).

P.S. What's a shame in C++, is that you cannot add a member to existing class. There's no low-level reason for that. If it would be possible, you could decouple header and cpp dependencies by not declaring private functions in the class definition header.

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