温馨提示×

c++中的operator怎么使用

c++
小亿
105
2023-12-16 23:38:09
栏目: 编程语言

在C++中,operator(运算符)可以用于定义类的成员函数,重载运算符的操作。

要使用operator,需要在类中定义一个成员函数,函数名以"operator"开头,后接要重载的运算符。例如,重载"+“运算符的函数名为"operator+”。

下面是一个示例,展示如何在C++中使用operator重载"+"运算符:

#include <iostream>

class Complex {
private:
    double real;
    double imaginary;

public:
    Complex(double r = 0.0, double i = 0.0) : real(r), imaginary(i) {}

    // 重载"+"运算符
    Complex operator+(const Complex& other) {
        double sum_real = this->real + other.real;
        double sum_imaginary = this->imaginary + other.imaginary;
        return Complex(sum_real, sum_imaginary);
    }

    void print() {
        std::cout << real << " + " << imaginary << "i" << std::endl;
    }
};

int main() {
    Complex c1(1.0, 2.0);
    Complex c2(3.0, 4.0);

    Complex c3 = c1 + c2; // 使用重载的"+"运算符
    c3.print(); // 输出:4 + 6i

    return 0;
}

在上述示例中,我们定义了一个Complex类,其中包含了一个重载的"+“运算符。在主函数中,我们创建了两个Complex对象c1和c2,并使用重载的”+"运算符将它们相加赋值给c3。最后,我们调用c3的print函数输出结果。

需要注意的是,C++中有一些运算符无法重载,如".“、”::“、”?"等运算符。此外,还需要注意运算符重载的规则和限制,比如重载运算符的参数和返回值类型等。

0