跳到主要内容

C++ 编程:使用运算符重载减去复数

为了理解这个例子,你应该掌握以下 C++ 编程 主题的知识:

由于 - 是一个二元运算符(操作两个操作数的运算符),其中一个操作数应作为参数传递给运算符函数,其余过程与一元运算符的重载类似。

示例:二元运算符重载以减去复数

#include <iostream>
using namespace std;

class Complex
{
private:
float real;
float imag;
public:
Complex(): real(0), imag(0){ }
void input()
{
cout << "请输入实部和虚部,依次为:";
cin >> real;
cin >> imag;
}

// 运算符重载
Complex operator - (Complex c2)
{
Complex temp;
temp.real = real - c2.real;
temp.imag = imag - c2.imag;

return temp;
}

void output()
{
if(imag < 0)


cout << "输出复数:"<< real << imag << "i";
else
cout << "输出复数:" << real << "+" << imag << "i";
}
};

int main()
{
Complex c1, c2, result;

cout << "输入第一个复数:\n";
c1.input();

cout << "输入第二个复数:\n";
c2.input();

// 在 C++ 编程中,对于二元运算符的重载,
// 编译器总是假设运算符右侧的对象作为参数。
result = c1 - c2;
result.output();

return 0;
}

在这个程序中,创建了三个类型为 Complex 的对象,并且用户被要求输入两个复数的实部和虚部,这些数据被存储在 c1c2 对象中。

然后执行语句 result = c1 - c2。这条语句调用了运算符函数 Complex operator - (Complex c2)

当执行 result = c1 - c2 时,c2 作为参数传递给了运算符函数。

在 C++ 编程中,对于二元运算符的重载,编译器总是假设运算符右侧的对象作为参数。

然后,这个函数将结果复数(对象)返回给 main() 函数,随后显示在屏幕上。

虽然,本教程包含了 - 运算符的重载,但 C++ 编程中的二元运算符如:+*<+= 等都可以以类似的方式进行重载。