编写运算符方法的实现
所以我有一个 LongInt 类,它将为 + 和 * 运算符提供新的定义。头文件中的初始化如下所示:
friend LongInt operator+(const LongInt& x, const LongInt& y);
friend LongInt operator*(const LongInt& x, const LongInt& y);
但是,在我的实现文件中,我定义了标头中找到的方法,VS 无法识别标头中列出的operator+ 函数或operator* 函数。我正在使用代码:
friend LongInt LongInt::operator+(const LongInt& x, const LongInt& y)
{
}
并且
friend LongInt LongInt::operator*(const LongInt& x, const LongInt& y)
{
}
当我尝试定义运算符时,关于为什么此代码不起作用的任何想法?
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)
{
}
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
friend
关键字仅在类内部声明或定义运算符时使用;当在类内部将运算符声明为friend
并在其他地方定义它时,friend
仅用于声明,而不用于定义。此外,在类中声明为friend
的函数实际上是命名空间范围内的自由函数,而不是类成员。因此,您的定义应该看起来更像是:如需进一步阅读材料,请阅读以下页面:C++ 常见问题解答:朋友< /a>
The
friend
keyword is only used when declaring or defining the operator inside of a class; when declaring the operator as afriend
inside of the class and defining it elsewhere,friend
is only used on the declaration, not the definition. Also, functions declared asfriend
inside a class are in fact free functions in namespace scope, not class members. So, your definitions should look more like:For further reading material, read over the following page: C++ FAQ: Friends
您正在重写运算符...您使用运算符“调用”它:
You're overriding an operator ... you "call" it using the operator: