MST

星途 面试题库

面试题:C++自定义运算符重载与表达式求值

假设有一个自定义的复数类Complex,包含实部和虚部。请实现该类,并对`+`、`*`运算符进行重载,使得能够正确计算两个复数的加法和乘法。然后编写一段代码,使用重载后的运算符计算两个复数的表达式`(a + b) * c`,其中`a`、`b`、`c`为不同的复数对象。
28.2万 热度难度
编程语言C++

知识考点

AI 面试

面试题答案

一键面试
#include <iostream>

class Complex {
public:
    double real;
    double imag;

    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);
    }

    // 重载 * 运算符
    Complex operator*(const Complex& other) const {
        return Complex(real * other.real - imag * other.imag,
                       real * other.imag + imag * other.real);
    }
};

int main() {
    Complex a(1, 2);
    Complex b(3, 4);
    Complex c(5, 6);

    Complex result = (a + b) * c;

    std::cout << "结果: " << result.real << " + " << result.imag << "i" << std::endl;

    return 0;
}
  1. Complex类定义
    • 定义了realimag成员变量分别表示复数的实部和虚部。
    • 提供了一个构造函数,默认实部和虚部为0,也可以传入实部和虚部的值。
  2. 运算符重载
    • operator+重载了加法运算符,返回两个复数相加后的结果。
    • operator*重载了乘法运算符,按照复数乘法规则返回结果。
  3. 主函数
    • 创建了三个复数对象abc
    • 通过重载后的运算符计算(a + b) * c,并输出结果。