1、声明一个复数类Complex(类私有数据成员为double型的real和image) 2、定义构造函数,用于指定复数的实部与虚部。 3、定义取反成员函数,调用时能返回该复数的相反数(实部、虚部分别是原数的相反数)。 4、定义成员函数Print(),调用该函数时,以格式(real, image)输出当前对象。 5、编写加法友元函数,以复数对象c1,c2为参数,求两个复数对象相加之和。 6、主程序实现: (1)读入两个实数,用于初始化对象c1。 (2)读入两个实数,用于初始化对象c2。 (3)计算c1与c2相加结果,并输出。 (4)计算c2的相反数与c1相加结果,并输出。 输入格式: 输入有两行: 第一行是复数c1的实部与虚部,以空格分隔; 第二行是复数c2的实部与虚部,以空格分隔。 输出格式: 输出共三行: 第一行是c1与c2之和; 第二行是c2的相反数与c1之和; 第三行是c2 。
时间: 2023-05-30 22:03:39 浏览: 132
#include<iostream>
using namespace std;
class Complex{
private:
double real,image;
public:
Complex(double a=0,double b=0):real(a),image(b){}
Complex operator-(){
return Complex(-real,-image);
}
void Print(){
cout<<"("<<real<<", "<<image<<")"<<endl;
}
friend Complex operator+(Complex a,Complex b){
return Complex(a.real+b.real,a.image+b.image);
}
};
int main(){
double a,b,c,d;
cin>>a>>b>>c>>d;
Complex c1(a,b),c2(c,d),sum,ans;
sum=c1+c2;
ans=-c2+c1;
sum.Print();
ans.Print();
c2.Print();
return 0;
}
相关问题
编写一个复数类模板complex,其数据成员real和image
好的,下面是一个简单的复数类模板complex的实现:
```cpp
template<typename T>
class complex {
public:
T real;
T image;
complex(T r = 0, T i = 0) : real(r), image(i) {}
complex<T> operator+(const complex<T>& other) const {
return complex<T>(real + other.real, image + other.image);
}
complex<T> operator-(const complex<T>& other) const {
return complex<T>(real - other.real, image - other.image);
}
complex<T> operator*(const complex<T>& other) const {
return complex<T>(real * other.real - image * other.image, real * other.image + image * other.real);
}
complex<T> operator/(const complex<T>& other) const {
T denominator = other.real * other.real + other.image * other.image;
return complex<T>((real * other.real + image * other.image) / denominator, (image * other.real - real * other.image) / denominator);
}
bool operator==(const complex<T>& other) const {
return (real == other.real) && (image == other.image);
}
bool operator!=(const complex<T>& other) const {
return !(*this == other);
}
friend std::ostream& operator<<(std::ostream& os, const complex<T>& c) {
os << c.real << "+" << c.image << "i";
return os;
}
};
```
这个类模板定义了一个复数类,包含实部和虚部两个数据成员。它的构造函数可以接受两个参数,分别是实部和虚部的值。同时,它还重载了加、减、乘、除、相等和不相等操作符,以及输出操作符。
定义复数类complex 1.定义数据成员实部和虚部 2.定义构造函数和析构函数 3.定义拷贝构造函数 4.定义showinfo成员函数
好的,下面是复数类complex的定义:
```cpp
class complex {
private:
double real; // 实部
double imag; // 虚部
public:
// 构造函数
complex(double r = 0, double i = 0) : real(r), imag(i) {}
// 拷贝构造函数
complex(const complex& c) : real(c.real), imag(c.imag) {}
// 析构函数
~complex() {}
// 显示复数信息
void showinfo() const {
cout << "(" << real << ", " << imag << "i)" << endl;
}
};
```
以上是一个简单的复数类complex的定义,它包括了实部和虚部两个数据成员,构造函数、析构函数和拷贝构造函数三个成员函数,以及一个用于显示复数信息的成员函数showinfo。