即使"friend class rect"在平方类中被评论,为什么它要改变矩形类的私有变量?

Even if "friend class rect" has been commented in square class why it is changing the private variable of rect class?

本文关键字:改变 变量 为什么 rect class friend 方类中 评论 即使      更新时间:2023-10-16

与以下程序混淆以供朋友类使用,请帮助我解决该

#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;";在Square类中,为什么我看到Rect类的成员已通过Square类更改为" R.Set_Data(S)";此功能在正常情况下,根据我的理解,只有当它是朋友类时,可以更改类的私人变量(因此,在下面的输出中,新的宽度和新的高度不应像我评论时更改"//朋友" rect;尽管有评论,但我看到了set_data函数的变量变量的变化,因此,如果仅通过将其他对象传递到任何函数来更改私人成员,则需要使用朋友类。

    output of the program :
    50
    4
    new width : 2
    new height : 2
    50 

set_data是类rect的一种方法。它将square的公共数据成员复制到rect的私人数据成员中。这没什么奇怪的,friend在这里无事可做。当您调用它时,您不会通过square修改rect的私人成员,而是通过类rect本身的公共方法set_data修改它们。从square获取新值并不意味着square修改它们。当您说" rect修改CC_12的私人成员"时,这意味着从类square的方法访问它们,这不是在这里。