操作符重载连加连减
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string.h>
#include <string>
using namespace std;//命名空间
class Complex
{
int a;
int b;
public:
Complex(int a, int b) :a(a), b(b)
{
}
friend Complex operator+(Complex& A1, Complex& A2);
friend Complex operator-(Complex& A1, Complex& A2);
};
Complex operator+(Complex& A1, Complex& A2)//operator+中间不能有空格
{
Complex temp(A1.a + A2.a, A1.b + A2.b);
return temp;
}
Complex operator-(Complex& A1, Complex& A2)//返回值不能加引用,返回的是值
{
Complex temp(A1.a - A2.a, A1.b - A2.b);
return temp;
}
int main(void)
{
Complex A1(3, 4);
Complex A2(4, 5);
Complex C1 = A1 + A2 + A1;
Complex C2 = A1 - A2 - A2;
return 0;
}
###### 运行结果及报错内容
E0349 no operator "-" matches these operands
E0349 no operator "+" matches these operands
###### 我的解答思路和尝试过的方法
如果操作符重载写在类内,连加连减是没有问题的,写成友元函数就出问题了
###### 我想要达到的结果
我想利用操作符重载连加连减
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string.h>
#include <string>
using namespace std;//命名空间
class Complex
{
int a;
int b;
public:
Complex(int a, int b) :a(a), b(b)
{
}
friend Complex operator+(const Complex& A1, const Complex& A2);//注意着两个参数必须是const Complex& 否则不能连加或者连减,因为a+b+c,会有临时变量,用complex&不能绑定临时变量,必须是const complex&才可以绑定临时变量
friend Complex operator-(const Complex& A1, const Complex& A2);
};
Complex operator+(const Complex& A1, const Complex& A2)//operator+中间不能有空格
{
Complex temp(A1.a + A2.a, A1.b + A2.b);
return temp;
}
Complex operator-(const Complex& A1, const Complex& A2)//返回值不能加引用,返回的是值
{
Complex temp(A1.a - A2.a, A1.b - A2.b);
return temp;
}
int main(void)
{
Complex A1(3, 4);
Complex A2(4, 5);
Complex C1 = A1 + A2 + A1;
Complex C2 = A1 - A2 - A2;
return 0;
}
在VS2010下编译没有报错啊
把参数改成const T&