C++好友运营商+超载
我对友元运算符重载感到困惑。如果我在头文件中编写友元运算符重载函数,那么没有问题,但是一旦将函数移动到类文件中,就会出现以下错误。我用谷歌搜索了一些示例,它们都将函数写入了头文件中。我做错了什么?谢谢。
...: error: expected ‘,’ or ‘...’ before ‘&’ token
...: error: ISO C++ forbids declaration of ‘statisticain’ with no type
...: error: ‘main_savitch_2C::statistician operator+(int)’ must have an argument of class or enumerated type
// a.h
class A
{
public:
friend A operator + (const A &a1, const A &a2);
};
// a.cpp
#include "a.h"
A operator + (const A &a1, const A &a2)
{
//
}
I'm confused about friend operator overloading. It has no problem if I write the friend operator overloading function within the header file, but it gives me the following errors once I moved the function to class file. I googled some samples and they all written the function in the header file. What did I do wrong? Thanks.
...: error: expected ‘,’ or ‘...’ before ‘&’ token
...: error: ISO C++ forbids declaration of ‘statisticain’ with no type
...: error: ‘main_savitch_2C::statistician operator+(int)’ must have an argument of class or enumerated type
// a.h
class A
{
public:
friend A operator + (const A &a1, const A &a2);
};
// a.cpp
#include "a.h"
A operator + (const A &a1, const A &a2)
{
//
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
从您收到的错误消息来看:
我认为您通过颠倒最后两个字母拼错了“statistician”(请注意,您有“statisticain”而不是“statistician”。)
这应该与是否
operator+ 无关
在头文件或 .cpp 文件中实现。From the error message you're getting:
I think that you misspelled "statistician" by reversing the last two letters (note that you have "statisticain" instead of "statistician.")
This should have nothing to do with whether
operator+
is implemented in the header or the .cpp file.我同意之前的回答。另外,如果我可能会问,当参数和返回类型都属于同一类时,为什么要让函数成为朋友呢?为什么不将其设为成员,以便第一个参数由
this
运算符隐式传递?I agree with the previous answer. Also, if I may ask, why make the function a
friend
when both arguments and the return type are of the same class? why not make it a member so the first argument is passed implicitly by thethis
operator?将两个参数版本移出类声明。或者只使用一个参数和 this 指针。
这是一个简短的现实世界示例。
Move the two param version out of the class declaration. Or just use one param and the this pointer.
Here's an abbreviated real world example.