2011-02-09 59 views
1

我对朋友操作符重载感到困惑。如果我在头文件中编写friend运算符重载函数,它没有问题,但是一旦将函数移动到类文件,它会给我以下错误。我搜索了一些样本,他们都在头文件中写了函数。我做错了什么?谢谢。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) 
{ 
    // 
} 
+0

该代码适用于我。你的**实际**代码是什么样的? – 2011-02-09 06:19:04

+1

因为每个人都给出了关于如何正确地重载operator +的建议,[这里是](http://codepad.org/8E9m5A7a)我的建议。 – 2011-02-09 06:58:12

回答

3

从你得到错误信息:

ISO C++ forbids declaration of ‘statisticain’ with no type 

我认为你拼错“统计学家”通过逆转的最后两个字母(请注意,你有“statisticain”而不是“统计员。 “)

这应该与头文件或.cpp文件中是否实现了operator+无关。

+0

哦,是的,我没有仔细阅读错误信息。非常感谢。 – Kyeteko 2011-02-09 07:18:20

1

我同意上一个答案。另外,如果我可能会问,为什么当这个函数和friend这两个参数和返回类型是同一个类时呢?为什么不把它作为一个成员,所以第一个参数是由this运算符隐式传递的?

+5

@ darkphoenix-(这可能属于评论而不是答案,顺便说一句)。你可以使`operator +`函数成为一个自由函数而不是一个成员函数,这样如果存在从其他类型到`A`的隐式转换,则可以考虑运算符。如果它是一个成员,那么如果第一个操作数不是`A`,则不会找到该函数。如果需要访问类数据成员,它将成为“朋友”。 – templatetypedef 2011-02-09 06:27:04

0

将两个参数版本移出类声明。或者只使用一个参数和这个指针。

下面是一个简短的现实世界的例子。

//complexnumber.h 
    class ComplexNumber 
    { 
     float _r; 
     float _i; 

     friend ComplexNumber operator+(const ComplexNumber&, const ComplexNumber&); 

     public: 
      ComplexNumber(float real, float img):_r(real),_i(img) {} 
      ComplexNumber& operator + (const ComplexNumber &other); 
    }; 

    ComplexNumber operator+(const ComplexNumber &c1, const ComplexNumber& c2); 


//complexnumber.h 
    ComplexNumber operator+(const ComplexNumber &c1, const ComplexNumber& c2) 
    { 
     return ComplexNumber(c1._r+c2._r, c1._i+c2._i); 
    } 


    // static 
    ComplexNumber& ComplexNumber::operator + (const ComplexNumber &other) 
    { 
     this->_r = this->_r + other._r; 
     this->_i = this->_i + other._i; 

     return *this; 

    }