簡體   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