C++全局重载运算符=

发布于 2024-10-18 08:28:59 字数 596 浏览 3 评论 0原文

可能的重复:
什么是“operator = 必须是非-”静态成员”是什么意思? (C++)

嗨,

我有以下代码...

// Header file
  struct dataRecord{
     size_t id;
     char name[gcNameLength];
  };

  void operator=(dataRecord &adr, const dataRecord &bdr);

gcc 在编译时如何给出以下错误。

error: ‘void operator=(dataRecord&, const dataRecord&)’ must be a nonstatic member function

感谢您的帮助。

Possible Duplicate:
What does “operator = must be a non-static member” mean? (C++)

Hi,

I have the following code...

// Header file
  struct dataRecord{
     size_t id;
     char name[gcNameLength];
  };

  void operator=(dataRecord &adr, const dataRecord &bdr);

How ever gcc gives me the following error when compiling.

error: ‘void operator=(dataRecord&, const dataRecord&)’ must be a nonstatic member function

Thanks for the help.

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

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

发布评论

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

评论(3

反目相谮 2024-10-25 08:29:02

“operator = 必须是”中所述非静态成员”是什么意思?,运算符重载需要是成员函数。

请注意,当您重载运算符=时,您应该返回对左操作数的引用,这样它就不会破坏流程并且允许使用如下表达式:

dataRecord r1;
dataRecord r2;
...
dataRecord r3 = r2 = r1;

As stated in What does “operator = must be a non-static member” mean?, the operator overload needs to be a member function.

Note that when you overload the operator=, you should return a reference to the left operand, so it won't break the flow and will allow expressios like:

dataRecord r1;
dataRecord r2;
...
dataRecord r3 = r2 = r1;
小嗷兮 2024-10-25 08:29:01

您需要在 struct dataRecord 本身上重载 = 操作。

像这样的东西:

struct dataRecord{
   size_t id;
   char name[gcNameLength];
   dataRecord& operator= (const dataRecord&) {
       // write overload code here
   }
};

You need to overload = operation on the struct dataRecord itself.

Something like:

struct dataRecord{
   size_t id;
   char name[gcNameLength];
   dataRecord& operator= (const dataRecord&) {
       // write overload code here
   }
};
情仇皆在手 2024-10-25 08:29:01

不存在“operator=”函数这样的东西。运算符必须是类或结构的成员。该函数的参数被视为右值。具有成员函数的对象是左值。

There is not such a thing as an operator= function. The operator has to be a member of the class or struct. The argument for that function is taken as the rvalue. The object with the member function is the lvalue.

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