繁体   English   中英

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

[英]operator overloading and non-member functions c++

我已经写了一个用于复数的类,其中重载了运算符+,并且一切正常,但是我需要将其实现为非成员函数,因此我不确定这样做的方式或好处。

这是我的代码.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;}

您可以向您的Complex类声明一个朋友

class Complex {

// blah....

    friend Complex operator+(Complex const& a, Complex const & b);
};

重载的操作员可以访问Complex的私有成员。

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

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等); //这是不可能的,因此,可以通过free函数对其进行重载。

您的班级正在通过公共接口(如aGetValue()和bGetValue)公开必要的信息。 因此,这个免费的重载+运算符函数不必成为类的朋友。

此外,与成员函数相比,优先选择非朋友非成员函数,因为它有助于降低封装程度。 这在这里说明==> http://www.drdobbs.com/cpp/how-non-member-functions-improve-encapsu/184401197?pgno=1

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM