MST

星途 面试题库

面试题:C++运算符重载之成员函数实现方式

请使用成员函数的方式重载C++中的二元加法运算符 '+',用于一个自定义的复数类Complex,该类有实部和虚部两个成员变量。要求实现正确的加法逻辑,并展示如何调用重载后的运算符。
38.7万 热度难度
编程语言C++

知识考点

AI 面试

面试题答案

一键面试
#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;
}

在上述代码中:

  1. Complex 类定义了两个私有成员变量 realimag 分别表示复数的实部和虚部。
  2. 构造函数用于初始化复数对象。
  3. operator+ 成员函数重载了 + 运算符,实现了复数的加法逻辑。
  4. display 函数用于输出复数的结果。
  5. main 函数中,创建了两个复数对象 c1c2,通过重载的 + 运算符将它们相加,并输出结果。