运算符重载和非成员函数 C++

operator overloading and non-member functions c++

本文关键字:函数 C++ 成员 重载 运算符      更新时间:2023-10-16

我已经为复数编写了一个类,其中我重载了运算符 +,一切正常,但是我需要将其实现为非成员函数,我不确定如何,或者为什么这样做有好处。

这是我的代码.h:

class Complex
{
private:
    double a;
    double b;
public:
    Complex();
    Complex(double aGiven);
    Complex(double aGiven, double bGiven);
    double aGetValue();
    double bGetValue();    
    double operator[](bool getB);
    Complex add(Complex &secondRational);
    Complex operator+(Complex &secondRational);
}

。.cpp:

Complex Complex::add(Complex &secondRational)
{
    double c = secondRational.aGetValue();
    double d = secondRational.bGetValue();
    double anew = a+c;
    double bnew = b+d;
    return Complex(anew,bnew);
}
Complex Complex::operator+(Complex &secondRational)
{
    return add(secondRational);
}

有关如何将这些作为非成员功能的任何帮助将不胜感激!

下面是类外的加法运算符:

Complex operator+(const Complex& lhs, const Complex& rhs) {
  //implement the math to add the two
  return Complex(lhs.aGetValue() + rhs.aGetValue(),
                 lhs.bGetValue() + rhs.bGetValue());
}

当然,您需要将aGetValue()bGetValue()声明为const

double aGetValue() const {return a;}
double bGetValue() const {return b;}

算术运算的常用方法是将运算符的自反版本定义为成员,将纯版本定义为非成员,并使用自反版本实现它们:

class complex {
public:
    const complex& operator+=(const complex& rhs) {
        real += rhs.real;
        imag += rhs.imag;
        return *this;
    }
};
complex operator+(const complex& lhs, const complex& rhs) {
    complex res(lhs);
    res += rhs;
    return res;
}

pippin1289 上面是如何解释的。

原因解释如下:

想象一下,需要使用类的对象作为

Complex c3 = 5 + c1;// for c3 object c1's real part (a) added with 5

作为C++保持操作数的顺序。编译器解析上述加法调用为5.operator+ (const Complex & other(;//这是不可能的因此,通过自由功能使其过载。

您的类通过公共接口(如 aGetValue(( 和 bGetValue(公开必要的信息。因此,这个免费的重载+运算符函数不一定是类的朋友。

此外,首选非友元非成员函数而不是成员函数,因为它有助于降低封装程度。这里解释了这一点==> http://www.drdobbs.com/cpp/how-non-member-functions-improve-encapsu/184401197?pgno=1

您可以向Complex类声明好友

class Complex {
// blah....
    friend Complex operator+(Complex const& a, Complex const & b);
};

重载的运算符可以访问 Complex 的私有成员。