编写一个简单复数类Scomplex,要求用友元函数重载“+”、“-”运算符,用成员函数重载“=”运算符,使之能够实现整数和复数的加法和减法,并且进行测试。
#include<iostream>
#include<string>
using namespace std;
class Scomplex
{
private:
double real, image;
public:
Scomplex(double re, double imag)
:real(re), image(imag)
{ }
Scomplex& operator = (Scomplex &a)
{
this->real = a.real;
this->image = a.image;
return *this;
}
friend Scomplex& operator + (Scomplex &a, Scomplex &b);
friend Scomplex& operator - (Scomplex &a, Scomplex &b);
friend ostream& operator << (ostream &os, Scomplex &c1);
};
ostream& operator << (ostream &os, Scomplex &c1)
{
return os << "(" << c1.real << ", " << c1.image << ")";
}
Scomplex& operator + (Scomplex &a, Scomplex &b)
{
a.real = a.real + b.real;
a.image = a.image + b.image;
return a;
}
Scomplex& operator - (Scomplex &a, Scomplex &b)
{
a.real = a.real - b.real;
a.image = a.image - b.image;
return a;
}
int main()
{
Scomplex c1(1,2);
Scomplex c2(2,3);
Scomplex c3(0,0);
c3 = c1 + c2;
cout << "c1 + c2:" << c3 << endl;
c3 = c2 - c1;
cout << "c1 - c2:" << c3 << endl;
return 0;
}
空间一点p的坐标为(x,y,z),其中x,y,z为整数。编写点类Point3D,重载空间两点之间的加”+”,减”-”运算符为相应三个坐标值分别进行加、减运算,要求实现空间两点之间的加”+”、减”-”、赋值”=”运算,空间两点间的比较”= =”运算。要求编写Point3D类的声明定义和测试程序。
#include<iostream>
using namespace std;
class Point3D
{
private:
int poi_x,poi_y,poi_z;
public:
Point3D(int x, int y, int z)
:poi_x(x), poi_y(y), poi_z(z)
{ }
int x(){ return poi_x; }
int y(){ return poi_y; }
int z(){ return poi_z; }
Point3D operator - (Point3D b)
{
return Point3D(this->poi_x - b.x(), this->poi_y - b.y(), this->poi_z - b.z());
}
void operator = (Point3D b)
{
this->poi_x = b.x();
this->poi_y = b.y();
this->poi_z = b.z();
}
// friend Point3D operator + (Point3D a, Point3D b);
friend ostream& operator << (ostream &os, Point3D &a)
{
os << "(" << a.poi_x << "," << a.poi_y << "," << a.poi_z << ")";
return os;
}
};
Point3D operator + (Point3D a, Point3D b)
{
return Point3D(a.x()+b.x(), a.y()+b.y(), a.z()+b.z());
}
bool operator == (Point3D a, Point3D b)
{
if(a.x()==b.x()&&a.y()==b.y()&&a.z()==b.z())
return true;
return false;
}
int main()
{
Point3D a(1,1,1);
Point3D b(2,2,2);
Point3D c(3,3,3);
a = c;
cout << a << endl;
if(a == b)
cout << "a与b相等" << endl;
else
cout << "a与b不相等" << endl;
if(a == c)
cout << "a与c相等" << endl;
else
cout << "a与c不相等" << endl;
return 0;
}