即使"friend class rect"在平方类中被评论,为什么它要改变矩形类的私有变量?
Even if "friend class rect" has been commented in square class why it is changing the private variable of rect class?
与以下程序混淆以供朋友类使用,请帮助我解决该
#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
的方法访问它们,这不是在这里。
相关文章:
- 变量没有改变?通过向量的函数调用
- 在向量内更改变量的值不会改变其在向量外的值
- C++11:具有互斥锁的线程看到原子变量的值发生变化,尽管这是唯一可以改变它的代码
- 为什么我可以改变常量对象中的成员变量,这是返回常量对象函数的结果?
- 标准在哪里定义了可变变量可以改变
- C++11:可变的 lambda 似乎没有改变变量?
- printf() 似乎改变了一个变量
- 为什么我的变量在单独的线程中修改时没有改变?C++/boost
- 为什么 Player.x 和 Player.y 变量没有改变?
- C - 如何将各处的静态函数称为改变其私有变量
- 即使"friend class rect"在平方类中被评论,为什么它要改变矩形类的私有变量?
- 为什么调用 CUDA 内核函数时这个类成员变量没有改变
- 全局变量的顺序会改变C /OpenGL的性能
- 为什么一个函数的末尾有常量这个词,即使它确实改变了一个变量
- 如何在C++中改变超类和子类的变量
- setRoomName不会改变变量roomName
- 不能改变变量的值
- 是否有一种方法可以改变变量在内存中的存储方式(位大小)
- Std::cout改变变量的值
- 使用引用改变变量的地址