Ctak Ctak - 1 year ago 63
C++ Question

Writing the implementation for an operator method

So I have a LongInt class that will have new definition for the + and * operators. The initialization in the header file looks like:

friend LongInt operator+(const LongInt& x, const LongInt& y);
friend LongInt operator*(const LongInt& x, const LongInt& y);

however in my implementation file, where I'm defining the methods found in the header, VS doesn't recognize the operator+ function or the operator* function as being listed in the header. I'm using the code:

friend LongInt LongInt::operator+(const LongInt& x, const LongInt& y)



friend LongInt LongInt::operator*(const LongInt& x, const LongInt& y)


Any ideas as to why this code wont work when I'm trying to define the operators?

Answer Source

The friend keyword is only used when declaring or defining the operator inside of a class; when declaring the operator as a friend inside of the class and defining it elsewhere, friend is only used on the declaration, not the definition. Also, functions declared as friend inside a class are in fact free functions in namespace scope, not class members. So, your definitions should look more like:

LongInt operator +(LongInt const& x, LongInt const& y) { /*...*/ }
LongInt operator *(LongInt const& x, LongInt const& y) { /*...*/ }

For further reading material, read over the following page: C++ FAQ: Friends

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download