开发者

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 heade开发者_高级运维r 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)
{

}

and

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?


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


You're overriding an operator ... you "call" it using the operator:

LongInt foo;
LongInt bar;
LongInt foobar = foo + bar;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜