假设有如下的代码:
T a,b,c;   //T为一个class
c = a + b;T的“+”号重载函数在很多文章上似乎有两种写法:
写法一:
T T::operator+(T& a, T& b)
{   
    T c;
    c.m = a.m + b.m;
    c.n = a.n + b.n;
    return c;
}
写法二:
T T::operator+(T& a)
{   
    T c;
    c.m  = this->m + a.m;
    c.n = this->n + a.n;
    return c;
}不知那一种是正确的?

解决方案 »

  1.   

    但是,在VC++中,方法一,会报错说:T::operator+()参数太!
      

  2.   

    1.wrong
    2.right1.//T T::operator+(T& a, T& b) // it is not member function of class T
    T operator+(T& a, T& b)  
    {   
        T c;
        c.m = a.m + b.m;
        c.n = a.n + b.n;
        return c;
    }
      

  3.   

    测试过,确实会有flash107(熊猫眼)说的报错情况。继续琢磨ing
      

  4.   

    To yym314(小鸟):问题不是那个,问题是:binary 'operator +' has too many parameters。怎么回事呢?请指教
      

  5.   

    operator + has two parameter!
    if you define the operator like this:
     T T::operator+(T& a, T& b), then operator+ take 3 paremater, so has too many parameters
    if you want to define operator+ in class T,it must like T T::operator+(T& a)
    else it must like T operator+(T& a, T& b)
      

  6.   

    双目运算符重载使用双参数的话,要使用友员才行,否则是要出错的!
    friend T operator+(T& a, T& b);T operator+(T& a, T& b)  // global function!
    {   
        T c;
        c.m = a.m + b.m;
        c.n = a.n + b.n;
        return c;
    }
      

  7.   

    T operator+(T& a, T& b)  应该加在什么地方?为什么我的上面加上它后会有这种报错:
    D:\VCѧϰ\Caculate\CaculateUnit.cpp(25) : warning C4244: '=' : conversion from 'double' to 'float', possible loss of data
    D:\VCѧϰ\Caculate\CaculateUnit.cpp(75) : error C2143: syntax error : missing ';' before '+'
    D:\VCѧϰ\Caculate\CaculateUnit.cpp(75) : error C2501: 'T' : missing storage-class or type specifiers
    D:\VCѧϰ\Caculate\CaculateUnit.cpp(75) : fatal error C1004: unexpected end of file found