
在 C++ 中,运算符重载是面向对象编程的一个重要特性,它允许我们为已有的运算符赋予新的含义。以复数类为例,我们可以实现加法、减法、赋值等常见运算符的重载,让代码更直观也更易读。

为了实现两个复数相加或相减,通常我们会将 + 和 - 作为非成员函数重载,并将其声明为类的友元,以便访问私有成员。

class Complex {
private:
double real;
double imag;
public:
Complex(double r = 0, double i = 0) : real(r), imag(i) {}
friend Complex operator+(const Complex& c1, const Complex& c2);
friend Complex operator-(const Complex& c1, const Complex& c2);
void print() const {
cout << real << " + " << imag << "i" << endl;
}
};
Complex operator+(const Complex& c1, const Complex& c2) {
return Complex(c1.real + c2.real, c1.imag + c2.imag);
}
Complex operator-(const Complex& c1, const Complex& c2) {
return Complex(c1.real - c2.real, c1.imag - c2.imag);
}使用时就像普通类型一样:
Complex a(3, 4); Complex b(1, 2); Complex c = a + b; // 调用 operator+ c.print(); // 输出 4 + 6i
这种方式的好处是支持左右操作数都为对象的情况,也能很好地处理隐式类型转换(比如 Complex + double)。
立即学习“C++免费学习笔记(深入)”;

当你的类包含动态分配资源时,就需要自定义赋值运算符来避免浅拷贝问题。即使在这个例子中没有动态内存,演示一下基本写法也是有帮助的。
class Complex {
// 同上...
public:
Complex& operator=(const Complex& other) {
if (this == &other) return *this;
real = other.real;
imag = other.imag;
return *this;
}
};这段代码中做了两件事:
虽然在这个简单例子中不涉及深拷贝,但这个模式可以防止潜在的问题,特别是在处理资源管理时非常关键。
C++ 区分前置和后置自增,它们的重载方式略有不同:
class Complex {
// ...
public:
Complex& operator++() { // 前置++
++real;
++imag;
return *this;
}
Complex operator++(int) { // 后置++
Complex temp(*this);
++(*this); // 调用前置版本
return temp;
}
};使用示例:
Complex c1(2, 3); Complex c2 = c1++; // c2 是原值,c1 自增了
注意后缀版本需要返回旧值,所以要先保存一份副本,再执行自增。
基本上就这些。
运算符重载的核心在于保持语义清晰,同时注意边界情况,比如自赋值、参数顺序、返回类型等。像比较运算符(如 ==、!=)也可以类似地实现,只要记住每个运算符的行为应该符合常规理解即可。
以上就是C++如何实现运算符重载 以复数类为例展示常用运算符实现的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号