// C++ 重载运算符示例
#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);
}
// 重载 << 运算符,用于输出
friend ostream& operator<<(ostream& os, const Complex& c);
// 重载 == 运算符
bool operator==(const Complex& other) const {
return (real == other.real && imag == other.imag);
}
};
// 实现 << 运算符的重载
ostream& operator<<(ostream& os, const Complex& c) {
os << c.real << " + " << c.imag << "i";
return os;
}
int main() {
Complex c1(3.5, 4.2);
Complex c2(2.1, 3.7);
Complex c3 = c1 + c2; // 使用重载的 + 运算符
cout << "c1 + c2 = " << c3 << endl;
if (c1 == c2) { // 使用重载的 == 运算符
cout << "c1 and c2 are equal" << endl;
} else {
cout << "c1 and c2 are not equal" << endl;
}
return 0;
}
Complex
类有一个构造函数,可以初始化复数的实部和虚部,默认值为 0。+
运算符:通过成员函数 operator+
实现两个复数相加的功能,返回一个新的 Complex
对象。<<
运算符:通过友元函数 operator<<
实现将 Complex
对象输出到流(如 cout
)中。这里使用了 friend
关键字,因为我们需要访问私有成员 real
和 imag
。==
运算符:通过成员函数 operator==
实现两个复数是否相等的判断。main
函数中,我们创建了两个 Complex
对象,并演示了如何使用重载的运算符进行加法和相等性比较。希望这个示例能帮助你理解 C++ 中的运算符重载!
上一篇:vc++runtime
下一篇:c++ 正则表达式
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站