C++运算符重载问题,,,,

来源:百度知道 编辑:UC知道 时间:2024/05/23 02:16:29
#include <iostream>
using namespace std;

class Test
{ public:
int a;
public:
Test(int a = 0)
{
Test::a = a;
}
friend Test operator+(Test&,Test&); //提示错误所在行,,,
friend Test& operator ++(Test&);

};
Test operator +(Test& temp1,Test& temp2)//+运算符重载函数
{
cout<<temp1.a<<"|"<<temp2.a<<endl;//在这里可以观察传递过来的引用对象的成员分量
Test result(temp1.a+temp2.a);
/ return result;
}
Test& operator ++(Test& temp)//++运算符重载函数
{
temp.a++;
return temp;
}
int main()
{
Test a(100);
Test c=a+a;
cout<<c.a<<endl;
c++;
cout<<c.a<<endl;
system("pause");
}
运行时提示错误为:
F:\Microsoft Visual Studio\MyProje

Test& operator+(Test&,Test&);
把这个放在类外面.因为你有两个操作数了.
然后
Test& operator +(Test& temp1,Test& temp2)//+运算符重载函数
{
cout<<temp1.a<<"|"<<temp2.a<<endl
Test result(temp1.a+temp2.a);
return result;
}

也可以把operator+写成类成员函数;
Test& operator+(Test&);
然后:
Test& Test::operator +(Test& temp1)
{
a += temp1.a;
return *this;
}

++运算符重载函数应该用作成员函数.比较好,因为只有一个操作数.