#include<iostream>
using namespace std;
class MyVector //定义向量类
{
public:
MyVector(int m); //构造函数,共有m个元素的向量,元素值预置为0
MyVector(const MyVector &v); //复制构造函数
~MyVector(); //析构函数:释放动态数组所占用的存储空间
friend istream &operator>>(istream &input, MyVector &d);
friend ostream &operator<<(ostream &output, const MyVector &d);
friend MyVector operator+(const MyVector &d1,const MyVector &d2);//向量相加,对应位置上的元素相加
friend MyVector operator-(const MyVector &d1,const MyVector &d2);//向量相减,对应位置上的元素相减
bool operator==(const MyVector &d);//判断两个矩阵是否相等,即对应位置上的所有元素是否相等
private:
int *Array; //Array 为动态数组指针,指向向量占用内存的起始地址
int num; //向量中元素个数
};
MyVector::MyVector(int m)
{
num=m;
Array=new int[num];
for(int i=0; i<num; ++i)
{
Array[i]=0;
}
}
MyVector::MyVector(const MyVector &v)
{
int i=0;
num=v.num;
Array=new int[num];
for(i=0; i<num; ++i)
Array[i]=v.Array[i];
}
MyVector::~MyVector()
{
delete Array;
}
bool MyVector::operator==(const MyVector &d)
{
int i=0;
if(num!=d.num)
return false;
for(i=0; i<num; ++i)
{
if(Array[i]!=d.Array[i])
return false;
}
return true;
}
istream &operator>>(istream &input, MyVector &d)
{
cout<<"输入"<<d.num<<"个向量元素";
int i=0;
for(i=0; i<d.num; ++i)
{
cin>>d.Array[i];
}
return input;
}
ostream &operator<<(ostream &output, const MyVector &d)
{
cout<<'(';
int i=0;
for(i=0; i<d.num-1; ++i)
{
cout<<d.Array[i]<<',';
}
cout<<d.Array[i]<<')';
return output;
}
MyVector operator+(const MyVector &d1,const MyVector &d2)
{
if(d1.num!=d2.num)
{
cout<<"erorr";
}
else
{
int i=0;
MyVector d(d1.num);
for(i=0; i<d1.num; ++i)
{
d.Array[i]=d1.Array[i]+d2.Array[i];
}
return d;
}
}
MyVector operator-(const MyVector &d1,const MyVector &d2)
{
if(d1.num!=d2.num)
{
cout<<"error";
}
else
{
int i=0;
MyVector d(d1.num);
for(i=0; i<d1.num; ++i)
{
d.Array[i]=d1.Array[i]-d2.Array[i];
}
return d;
}
}
int main()
{
MyVector d1(5),d2(5);
cout<<"输入d1——";
cin>>d1;
cout<<"输入d2——";
cin>>d2;
cout<<"d1="<<d1<<endl;
cout<<"d2="<<d2<<endl;
cout<<"d1+d2="<<d1+d2<<endl;
cout<<"d1-d2="<<d1-d2<<endl;
cout<<"d1"<<((d1==d2)?"==":"!=")<<"d2"<<endl;
return 0;
}
2015.5.19我的向量
最新推荐文章于 2022-09-06 23:25:34 发布