-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;
}

根据朋友指南,如果我们使用朋友类,那么它可以访问和修改其朋友类的私有成员,所以即使我已经评论了“//朋友类 rect;” 在方形类中,为什么我看到 rect 类的成员已被方形类更改为“r.set_data(s);” 这个函数在正常情况下,根据我的理解,一个类的私有变量只有在它是朋友类时才能改变(所以在下面的输出中,新的宽度和新的高度不应该改变,因为我已经评论了“//朋友类矩形;”但是即使它被评论了,我也看到了 set_data 函数对 rect 类的变量的更改,所以如果仅通过将其他对象传递给任何函数来更改私有成员,那么需要使用朋友类。

    output of the program :

    50
    4

    new width : 2
    new height : 2
    50 
4

1 回答 1

3

set_data是类的方法rect。它将 a 的公共数据成员复制square到 的私有数据成员中rect。没有什么奇怪的,friend也与这里无关。当您调用它时,您不会修改rectby的私有成员,而是通过类本身square的公共方法修改它们。从 a 中获取新值并不意味着修改它们。当您说“修改by 的私有成员”时,它意味着从类的方法访问它们,这里不是这种情况。set_datarectsquaresquarerectsquaresquare

于 2016-06-22T07:32:02.587 回答