-2

フレンドクラスで使用する以下のプログラムと混同しています。解決するのを手伝ってください

#include <iostream>

using namespace std;

class square;

class rect {
    public :
            rect(int w = 0, int h = 0) : width(w), height(h), volume(w*h) {}
            void set_data(square &);
            int get_width(void)
            {
                return width;
            }
            int get_height(void)
            {
                return height;
            }
            int get_volume(void);
    private :
            int width;
            int height;
            int volume;
};

class square {
    public :
            square(int w = 0, int h = 0) : width(w), height(h), volume(w*h) {}
            int width;
            int height;
            int get_volume(void);
**//          friend class rect;**
    private :
            int volume;
};

void rect :: set_data(square &s)
{
    width = s.width; *// the variables of rect class are private and it shud not allow to change as i have commented "//friend class rect;" the sentence in square class.* 
    height = s.height;
}

int rect :: get_volume(void)
{
    return volume;
}

int square :: get_volume(void)
{
    return volume;
}

int main()
{
    rect r(5,10);
    cout<<r.get_volume()<<endl;
    square s(2,2);
    cout<<s.get_volume()<<endl;
    cout<<endl;
    cout<<endl;
    r.set_data(s); *// accessing the private members of the rect class through object of square class*
    cout<<"new width : "<<r.get_width()<<endl;
    cout<<"new height : "<<r.get_height()<<endl;
    cout<<r.get_volume()<<endl;
    return 0;
}

フレンドガイドラインに従って、フレンドクラスを使用すると、フレンドクラスのプライベートメンバーにアクセスして変更できるため、「//friend class rect;」とコメントしましたが。正方形クラスで、rect クラスのメンバーが「r.set_data(s);」によって正方形クラスによって変更されたのはなぜですか? この関数私の理解によると、通常の状態では、クラスのプライベート変数はそれがフレンドクラスである場合にのみ変更できます(したがって、以下の出力では、「//friend class rect;」とコメントしたように、新しい幅と新しい高さを変更しないでください。しかし、コメントされていても、set_data関数によってrectクラスの変数が変更されているのを見ているので、他のオブジェクトを任意の関数に渡すだけでプライベートメンバーが変更された場合、フレンドクラスを使用する必要はありません。

    output of the program :

    50
    4

    new width : 2
    new height : 2
    50 
4

1 に答える 1

3

set_dataクラスのメソッドですrectsquareのパブリック データ メンバーをのプライベート データ メンバーにコピーしrectます。何もおかしなことでfriendはないし、ここでは何の関係もありません。それを呼び出すとき、rectbyのプライベート メンバーを変更するのではなく、クラス自体squareのパブリック メソッドによって変更します。から新しい値を取得しても、がそれらを変更するわけではありません。「 byのプライベート メンバーを変更する」と言うとき、それは class のメソッドからそれらにアクセスすることを意味しますが、ここではそうではありません。set_datarectsquaresquarerectsquaresquare

于 2016-06-22T07:32:02.587 に答える