[英]What happens when Classes that are friends have same name member variables
In C++, what happens when I have the following 在C ++中,当我遇到以下情况时会发生什么
class House
{
public:
House();
~House();
private:
int* m_peopleInside;
friend class Room;
};
and then in the constructor of House this is set 然后在House的构造函数中设置
m_peopleInside = new int[5];
m_peopleInside[4] = 2;
and 和
class Room
{
public:
Room();
~Room();
Update();
private:
int* m_peopleInside;
};
Then in the Room.Update() I use m_peopleInside something like this. 然后在Room.Update()中,我使用m_peopleInside这样的东西。
&m_peopleInside[4];
It's my understanding that the friend class will allow the Room class to access private members of the House class. 据我了解,朋友类将允许Room类访问House类的私有成员。 So which m_peopleInside would be used? 那么将使用哪个m_peopleInside?
I should add that in this case, m_peopleInside is being used as an array. 我应该补充一点,在这种情况下,m_peopleInside被用作数组。
It's an instance variable. 这是一个实例变量。 So it needs an instance to act on. 因此,需要实例来对其进行操作。 If no instance is provided, then it is the same as this->m_peopleInside
, which means it refers to the instance on which the function was called. 如果没有提供实例,则它与this->m_peopleInside
相同,这意味着它引用了在其上调用函数的实例。 So, for example, if this is your function: 因此,例如,如果这是您的功能:
void Room::Update() {
// these two are the same, they null the member of the Room object
m_peopleInside = nullptr;
this->m_peopleInside = nullptr;
House h;
// should be pretty obvious what this does
h.m_peopleInside = nullptr;
}
It's my understanding that the friend class will allow the
Room
class to access private members of the House class. 据我了解,朋友类将允许Room
类访问House类的私有成员。
That is correct. 那是对的。
So which
m_peopleInside
would be used? 那么将使用哪个m_peopleInside
?
To access the m_peopleInside
member of a House
object, you will need an object or pointer of type House
. 要访问House
对象的m_peopleInside
成员,您将需要House
类型的对象或指针。
In Room::update()
, if you simply use m_peopleInside
, it will be member variable of Room
, not House
. 在Room::update()
,如果仅使用m_peopleInside
,它将是Room
成员变量,而不是House
。
When you use "m_peopleInside" inside "Room.Update()" you will definitely use the data member of "Room". 在“ Room.Update()”中使用“ m_peopleInside”时,您肯定会使用“ Room”的数据成员。 Your understanding of "friend" classes is not so correct. 您对“朋友”课程的理解不太正确。 To make it clear, suppose that you have an object "x" from the class "House" in one of the methods of the class "Room', like "Update()" for example. Then, the following code is correct in this method: 为了清楚起见,假设您在“房间”类的方法之一(例如“ Update()”)中有一个来自“房屋”类的对象“ x”,那么下面的代码是正确的方法:
cout << x.m_peopleInside;
Although "m_peopleInside" is private in "House", it is accessible from Room's methods, because the class "House" declares that "Room" is a friend of his. 尽管“ m_peopleInside”在“房屋”中是私有的,但是可以通过Room的方法进行访问,因为“房屋”类声明“ Room”是他的朋友。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.