重载运算符 +, -, = ,<< ,>>实现对向量的操作时出现了问题!
// 运算符重载.cpp: 定义控制台应用程序的入口点。// 两个向量相加,相加,赋值运算
#include"stdafx.h"
#include<iostream>
#include<typeinfo>
using namespace std;
class Vector
{
int vec[5];
public:
Vector(int v[5]);
Vector();
Vector(Vector&);
Vector operator +(Vector&);
Vector operator -(Vector&);
Vector operator =(Vector&);
friend ostream& operator <<(ostream& out, Vector& v);
friend istream& operator >>(istream& in, Vector& v);
};
Vector::Vector(int v[5])
{
for (int i = 0; i < 5; i++)
vec[i] = v[i];
}
Vector::Vector()
{
for (int i = 0; i < 5; i++)
vec[i] = 0;
}
Vector::Vector(Vector& v)
{
for (int i = 0; i < 5; i++)
vec[i] = v.vec[i];
}
Vector Vector::operator + (Vector& v)// 重载 +
{
Vector z;
for (int i = 0; i < 5; i++)
z.vec[i] = vec[i] + v.vec[i];
return z;
}
Vector Vector::operator - (Vector& v)//重载 -
{
Vector z;
for (int i = 0; i < 5; i++)
z.vec[i] = vec[i] - v.vec[i];
return z;
}
Vector Vector::operator = (Vector& v) //重载 =
{
if (&v != this)
{
for (int i = 0; i < 5; i++)
this->vec[i] = v.vec[i];
}
return *this;
}
ostream& operator <<(ostream& out, Vector& v)//重载 <<
{
for (int i = 0; i < 5; i++)
out << v.vec[i]<<",";
return out;
}
istream& operator >>(istream& in, Vector& v)//重载 >>
{
for (int i = 0; i < 5; i++)
in >> v.vec[i];
return in;
}
//测试Vector类
int main()
{
int a[5], b[5];
cout << "v1:";
for (int i = 0; i < 5; i++)
cin >> a[i];
cout << "v2:";
for (int i = 0; i < 5; i++)
cin >> b[i];
Vector v1(a), v2(b), v3, v4,v5,v6,v7;
v3=v1 ;
v4=v2; //测试重载 = 运算符,可成功赋值
cout << "v5:";
cin >> v5; // 测试重载 >>运算符, 可成功输入
cout << endl << endl;
cout << v3 << endl<<endl;
cout << v4 << endl<<endl; //测试重载 << 运算符,可成功输出
cout << v5 << endl<<endl;
cout<<typeid(v1 + v2).name()<<endl; //测试重载 + 运算符, 输出 class Vector
cout<<typeid(v2 - v1).name()<<endl<<endl; //测试重载 - 运算符, 输出 class Vector
/*但!!!! 问题啊来了。当你把重载的运算符结合在一起时就会报错,以下报错代码*/
v6 = v1 + v2;
v7 = v2 - v1;
cout << v1 + v2 << endl;
cout << v2 - v1 << endl;
//求解?
system("pause");
return 0;
}
========================================================================================
错误提示:
C2679 二进制“<<”: 没有找到接受“Vector”类型的右操作数的运算符(或没有可接受的转换)
C2679 二进制“>>”: 没有找到接受“Vector”类型的右操作数的运算符(或没有可接受的转换)
C2679 二进制“=”: 没有找到接受“Vector”类型的右操作数的运算符(或没有可接受的转换)
C2679 二进制“=”: 没有找到接受“Vector”类型的右操作数的运算符(或没有可接受的转换)
========================================================================================
错误提示是什么意思??那些运算符我都是有重载的,而且前面的测试都没有问题,就在这四条语句
出现了问题。
v6 = v1 + v2;
v7 = v2 - v1;
cout << v1 + v2 << endl;
cout << v2 - v1 << endl;
有谁知道怎么改,并且知道原理么?