2017-06-01 46 views
2
#include<iostream> 
using namespace std; 

class test 
{ 
    int i; 
    string s; 

    public: 
    test(){} 

    test(int a,string b) 
    { 
     i=a; 
     s=b; 
    } 

    void operator = (test &temp) 
    { 
     cout<<"In assignment operator"<<endl; 
     i=temp.i; 
     s=temp.s; 
    } 

    test operator + (test &temp) 
    { 
     test newobj; 
     newobj.i=i+temp.i; 
     newobj.s=s+" "+temp.s; 
     return newobj; 
    } 
}; 

main() 
{ 
    test t1(5,"ABC"); 
    test t2; 
    t2=t1; 
    test t3; 
    t3=t1+t2; 
} 

问题:t3=t1+t2给了我一个错误。我想重载=和+运算符并按照上图所示使用它们。我错在哪里?我想明确定义一个赋值运算符重载,即使编译器提供了一个。超载分配和加运算符

错误:从类型 'test' 的t3=t1+t2;

初始化的 'void test::operator=(test&)' void operator = (test &temp)

+0

这两个运营商应该把他们的参数作为'const的测试&'。 –

+0

参数需要是'const temp&';因为't1 + t2'是临时的,不能通过非const。 –

+0

如果有人能够在参数中解释const的使用,我们将非常感激。据我所知,const只是表示接收的对象的数据成员不能被改变。我可能错了。请帮忙。 –

回答

1

t1+t2参数1右值的类型的非const引用 '测试&' 无效初始化返回一个临时的test,不能绑定到引用非const(即test &),这就是为什么t3=t1+t2;失败。另一方面,临时可以被绑定到引用const(即const test&)。因此,您可以将参数类型更改为const test&,例如

void operator = (const test &temp) 
{ 
    cout<<"In assignment operator"<<endl; 
    i=temp.i; 
    s=temp.s; 
} 

BTW1:最好是用operator+做同样的事情。

BTW2:的operator=常规签名(并实施)为:

test& operator= (const test& temp) 
{ 
    cout<<"In assignment operator"<<endl; 
    i = temp.i; 
    s = temp.s; 
    return *this; 
} 
+0

谢谢。但不明白你对const的解释。通过接收测试对象为const,上述代码如何工作得很好?在赋值运算符重载函数中,为什么当我们仅仅将第二个对象的值赋给当前对象时,我们需要返回当前对象。假设t2 = t1,这里t2对象将调用=运算符并将接收t1对象的引用。那么我们只是将t1的值赋值给t2。为什么我们需要返回*这个? (即参考对象t2) –

+0

@DigeshPatel因为临时不能绑定到'test&',而是'const test&'。例如'test&t = test {};'会失败,但'const test&t = test {};'很好。 – songyuanyao

+0

@DigeshPatel对于你的第二个问题,可以像内置类型一样链接操作符。例如't1 = t2 = t3;'。 – songyuanyao