C++ globally overloaded operator= [duplicate]

2019-07-15 11:07发布

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.

3条回答
爷的心禁止访问
2楼-- · 2019-07-15 11:23

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.

查看更多
趁早两清
3楼-- · 2019-07-15 11:24

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;
查看更多
劫难
4楼-- · 2019-07-15 11:27

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
   }
};
查看更多
登录 后发表回答