#include <iostream>
using namespace std;
class Complex {
private:
double real;
double imag;
public:
Complex(double r = 0, double i = 0) : real(r), imag(i) {}
// 重载加法运算符
Complex operator+(const Complex& other) const {
return Complex(real + other.real, imag + other.imag);
}
// 重载减法运算符
Complex operator-(const Complex& other) const {
return Complex(real - other.real, imag - other.imag);
}
// 重载乘法运算符
Complex operator*(const Complex& other) const {
return Complex(real * other.real - imag * other.imag, real * other.imag + imag * other.real);
}
// 重载输出流运算符
friend ostream& operator<<(ostream& os, const Complex& c);
};
// 定义输出流运算符的实现
ostream& operator<<(ostream& os, const Complex& c) {
os << c.real << " + " << c.imag << "i";
return os;
}
int main() {
Complex c1(3.0, 4.0);
Complex c2(1.0, 2.0);
Complex sum = c1 + c2;
Complex diff = c1 - c2;
Complex prod = c1 * c2;
cout << "c1: " << c1 << endl;
cout << "c2: " << c2 << endl;
cout << "c1 + c2: " << sum << endl;
cout << "c1 - c2: " << diff << endl;
cout << "c1 * c2: " << prod << endl;
return 0;
}
类定义:
Complex
类用于表示复数,包含两个私有成员变量 real
和 imag
,分别表示复数的实部和虚部。构造函数:
Complex(double r = 0, double i = 0)
是一个带默认参数的构造函数,允许创建复数对象时指定实部和虚部的值,默认值为 0。运算符重载:
operator+
:重载了加法运算符,返回一个新的 Complex
对象,其值为两个复数相加的结果。operator-
:重载了减法运算符,返回一个新的 Complex
对象,其值为两个复数相减的结果。operator*
:重载了乘法运算符,返回一个新的 Complex
对象,其值为两个复数相乘的结果。友元函数:
friend ostream& operator<<(ostream& os, const Complex& c)
:重载了输出流运算符 <<
,使得可以直接使用 cout
输出 Complex
对象。这个函数是类的友元函数,可以访问类的私有成员。主函数:
Complex
对象 c1
和 c2
,并演示了如何使用重载的运算符进行加法、减法和乘法操作,最后将结果输出到控制台。通过这些代码和解释,您可以了解如何在 C++ 中重载运算符以扩展类的功能。
下一篇:c++字符串转化为数字
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站