0

I have a variable class that I am using to make scripting more easier in my program. I am trying to figure out an easy way to do something like the following:

myclass
{
protected:
    int _data;
...
}

when I overload operators with non-member functions such as the following:

int operator+(const int, const myclass);
int operator+(const int lhs, const myclass rhs)
{
    return lhs + rhs.GetData();
}

I have no problems until I try to overload an assignment operator with a non-member function.

int operator=(const int, const myclass);

This gives an error and won't compile. error C4430: Missing type specifier - int assumed. errir C2801 'operator =' must be a non-static member.

I just want to be able to have something like the following work:

myclass A(7);
int B = 5;
int C;
C = B + A;

how can I achieve this. I have tens of millions of lines of code that I just want to replace simple int's with myclass, but don't want to have to edit every use of this variable.

Note: edited to add error messages.

Final Edit: Solution found:

operator int() const { return _data; }

By adding the overload operator, I have no need to overload the assignment operator as a non-member function.

  • _"This gives an error and won't compile."_ Please [edit] your question, and specify the exact error message. – πάντα ῥεῖ Jan 07 '22 at 18:29
  • 1
    Useful reference: [The basics of operator overloading](https://stackoverflow.com/questions/4421706/what-are-the-basic-rules-and-idioms-for-operator-overloading/4421719#4421719). `operator=` as a non-member function is _very weird_. What are you trying to assign to? What's the return value? If you want to be able to write something like `int C = someMyClass + someInt;`, what you probably actually want is a conversion `operator int`. – Nathan Pierson Jan 07 '22 at 18:30
  • 1
    Does this answer your question? [What are the basic rules and idioms for operator overloading?](https://stackoverflow.com/questions/4421706/what-are-the-basic-rules-and-idioms-for-operator-overloading) – Richard Critten Jan 07 '22 at 18:32
  • No The basics of operator overloading does not answer it. But I did find a solution via overloading the typecast operation that did resolve the problem for me. – Chubby Monkey Jan 07 '22 at 20:43

0 Answers0