1

これは、 http://www.learncpp.com/cpp-tutorial/92-overloading-the-arithmetic-operators/からのコードの一部です。

私は、いくつかの独学の Web サイトや閲覧フォーラムから、オペレーターのオーバーロードについて調べてきました。別の方法を使用したオーバーロードについて質問しましたが、今では理解できました。そのQ&Aリンクはこちら定義されていない場合、これはどのように値を返しますか?

しかし、私が理解していない参照を伴うこの方法。コードを実装するさまざまな方法を試してみたところ、それほど複雑ではないいくつかの方法が機能することがわかりました。

これを行う方法は、クラスのインスタンスを演算子関数のパラメーターとして作成し、演算子関数内の一時的なインスタンスを作成し、それらの値を = 演算子で返すことです。この方法ははるかに複雑で、なぜこれが機能するのかについていくつかの問題があります。

質問はコードを下に進むにつれて説明されますが、ここに私が持っている 3 つの質問があります。
(質問 1) Ceteris parabis、パラメーターに const キーワードが必要なのはなぜですか? 変数を公開する場合は公開しないことはわかっていますが、なぜフレンド クラスがある場合、またはコードがクラス自体の内部に記述されている場合、const を使用する必要があるのでしょうか。
(質問 2) フレンド関数をクラス内に配置した場合でも、"friend" というキーワードが必要なのはなぜですか?
(質問 3) クラス c1 と c2 はどこで初期化されますか? それらの参照はありますが、戻るまで初期化はありませんが、それは参照の下にあります。コンパイル時にエラーが発生すると思います。

class Cents
{
private:
    int m_nCents;

public:
    Cents(int nCents) { m_nCents = nCents; }
    //I know this assigns each
    //instance to the private variable m_nCents since it's private.

    // Add Cents + Cents 
    friend Cents operator+(const Cents &c1, const Cents &c2); 

    //why do we need
    //to make this a friend? why can't we just put it inside the class and not  
    //use the "friend" keyword? also why do I need to make the variables public
    //if i remove const from the parameters

    int GetCents() { return m_nCents; } 
    //I know how this is used to return the
    // variable stored in m_nCents, in this program it is for cout
};

// note: this function is not a member function!
Cents operator+(const Cents &c1, const Cents &c2)
//where are these references 
//actually defined? I do not see c1 or c2 anywhere except in the return, but
//that is below the code that is referencing the class
{
    // use the Cents constructor and operator+(int, int)
    return Cents(c1.m_nCents + c2.m_nCents);
}

int main()
{
    Cents cCents1(6);
    Cents cCents2(8);
    Cents cCentsSum = cCents1 + cCents2;
    std::cout << "I have " << cCentsSum .GetCents() << " cents." << std::endl;

    return 0;
}
4

2 に答える 2