/ 猿问

# c++容器问题？

2018-09-18 10:06:01

//2.设向量X=(x1,x2,......,xn)和Y=(y1,y2,……,yn),它们之间的加、减分别定义为： X+Y=(x1+y1,x2+y2,……,xn+yn) X-Y=(x1-y1,x2-y2,……,xn-yn)
//编程序定义向量类Vector ,重载运算符”+”、”-“、”=”,实现向量之间的加、减和赋值运算;用重载运算符”>>”、”<<”做向量的输入/输出操作。注意检测运算的合法性。

## 1 回答

#include<iostream>

using namespace std;

class Vector
{
public:
Vector();
Vector(double a,double b);
Vector operator+(Vector &);
Vector operator-(Vector &);
Vector& operator==(Vector &c)
{
x=c.x;
y=c.y;
return *this;
}
friend ostream & operator << (ostream &,Vector &);
friend istream & operator >> (istream &,Vector &);
void display();
private:
double x;
double y;
};

Vector::Vector()
{
x=0;
y=0;
}

Vector::Vector(double a,double b)
{
x=a;
y=b;
}

Vector Vector::operator+(Vector &a)
{
}

Vector Vector::operator-(Vector &b)
{
Vector sub;
sub.x=x-b.x;
sub.y=y-b.y;
return sub;
}

ostream & operator << (ostream &out,Vector &d)
{
out << d.x << " " <<d.y << endl ;
return out;
}

istream & operator >> (istream &in,Vector &e)
{
cin >> e.x >> e.y ;
return in;
}

void Vector::display()
{
cout << x << " " << y << endl ;
}

int main()
{
Vector c1(1.1,2.2),c2(3.3,4.4),c3(5.5,6.6),c4,t;
t=c1+c2; //重载+
t.display(); //显示结果
t=c3-c2; //重载-
t.display();

c2==c1; //重载=，讲C1中的值赋值给c2中的
c2.display(); //显示复制结果，应该与c1的值一样

cin >> c4 ;
cout << c4 ;
return 0;
}

• 1 回答
• 0 关注
• 403 浏览

0/150