用c++写一段运算符重载
时间: 2023-11-22 16:00:36 浏览: 36
运算符重载是 C++ 的一个重要特性,但是 C 语言并不支持运算符重载。因此,无法直接用 C 语言写一段运算符重载的代码。
如果你想使用运算符重载功能,可以考虑使用 C++ 编写。下面是一个简单的例子,展示了如何重载加号运算符来实现两个复数的加法:
```cpp
#include <iostream>
class Complex {
public:
Complex(double real = 0.0, double imag = 0.0)
: m_real(real), m_imag(imag) {}
// 重载加号运算符
Complex operator+(const Complex& other) const {
return Complex(m_real + other.m_real, m_imag + other.m_imag);
}
void print() const {
std::cout << m_real << " + " << m_imag << "i" << std::endl;
}
private:
double m_real;
double m_imag;
};
int main() {
Complex c1(1.0, 2.0);
Complex c2(2.0, 3.0);
Complex c3 = c1 + c2; // 调用加号运算符重载函数
c3.print(); // 输出结果为:3 + 5i
return 0;
}
```
在上面的代码中,我们定义了一个名为 Complex 的类,它表示一个复数。在类中,我们重载了加号运算符,使得两个 Complex 对象可以通过加号运算符相加。在主函数中,我们创建了两个 Complex 对象,并将它们相加,然后输出结果。