#include <iostream>
#include <string>
using namespace std;
class Complex {//复数类定义
public://external interface
Complex(double r = 0.0, double i = 0.0) :real(r), image(i) {}//constructor function
Complex operator+(const Complex& c2) const;//make operator + to be member function
Complex operator-(const Complex& c2) const;//like prior
/**
使用const关键字进行说明的成员函数,称为常成员函数。
只有常成员函数才有资格操作常量或常对象,没有使用const关键字说明的成员函数不能用来操作常对象
*/
void display() const;
private:
double real, image;
};
Complex Complex::operator+(const Complex& c2) const {//重载运算符函数实现
return Complex(real + c2.real, image + c2.image);//创建一个临时无名对象作为返回值
}
Complex Complex::operator-(const Complex& c2) const {//重载运算符函数实现;、
return Complex(real - c2.real, image - c2.image);//创建一个临时无名对象作为返回值
}
void Complex::display() const {
cout << "(" << real << "," << image << ")" << endl;
}
in
47.C++复数类加减运算为重载为成员函数形式
最新推荐文章于 2024-04-24 23:57:52 发布