面试题答案
一键面试#include <iostream>
class Complex {
private:
double real;
double imag;
public:
Complex(double r = 0, double i = 0) : real(r), imag(i) {}
// 重载二元加法运算符 '+'
Complex operator+(const Complex& other) {
return Complex(real + other.real, imag + other.imag);
}
void display() {
std::cout << real;
if (imag >= 0) {
std::cout << " + " << imag << "i";
} else {
std::cout << " - " << (-imag) << "i";
}
std::cout << std::endl;
}
};
int main() {
Complex c1(3, 4);
Complex c2(1, -2);
Complex result = c1 + c2;
std::cout << "The result of addition is: ";
result.display();
return 0;
}
在上述代码中:
Complex
类定义了两个私有成员变量real
和imag
分别表示复数的实部和虚部。- 构造函数用于初始化复数对象。
operator+
成员函数重载了+
运算符,实现了复数的加法逻辑。display
函数用于输出复数的结果。- 在
main
函数中,创建了两个复数对象c1
和c2
,通过重载的+
运算符将它们相加,并输出结果。