4

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.

Community
  • 1
  • 1
Thomas
  • 2,939
  • 6
  • 32
  • 29
  • "must be a nonstatic member function" - what's not clear here? – Nikolai Fetissov Feb 18 '11 at 02:49
  • The error message is telling the problem very precisely in this case: if you're going to overload `operator=`, you can't do it as a global function -- you have to use a non-static member function (the usual reason to use a global is to allow conversions on the left operand, but that wouldn't apply in the case of assignment anyway). – Jerry Coffin Feb 18 '11 at 02:50
  • So it must be part of the struct can not be global. – Thomas Feb 18 '11 at 02:50
  • Part of the error message says it all- **must be a nonstatic member function**. – Mahesh Feb 18 '11 at 02:51

3 Answers3

5

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
   }
};
Pablo Santa Cruz
  • 176,835
  • 32
  • 241
  • 292
2

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.

Javier
  • 2,818
  • 3
  • 19
  • 20
2

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;
Community
  • 1
  • 1
fbafelipe
  • 4,862
  • 2
  • 25
  • 40
  • I don't mind returning void from operator=. Especially if it is expensive to copy. I know the general expected behavior would be to return a reference but this has to be measured against usage costs. – Martin York Feb 18 '11 at 03:07
  • Returning a reference isn't expensive. If the function is inline, most compilers will optimize it and will be free. – fbafelipe Feb 18 '11 at 03:11