与复制构造函数和私有成员的混淆 [英] Confusion with copy constructor and private member
问题描述
假设我有以下课程:
class Test
{
int num;
public:
Test(int x):num(x){}
Test(const Test &rhs):num(rhs.num+1){}
};
int main()
{
Test test(10);
Test copy = test;
}
副本中的 num
应该为 11
,而我的问题是关于副本构造函数内部的内容,为什么我们可以访问私有成员 num
使用 num
初始化副本中的 num
的 test
>?令我感到困惑的是,如果您键入 cout<<< test.num<< endl
,则当然是错误的,因为您正试图访问私有的 num
,但是如果您通过引用复制构造函数通过测试,则该方法有效,有人可以告诉我这里发生了什么吗?
The num
in the copy should be 11
, and my question is about inside the copy constructor, why can we access the private member num
of test
using num
to initialize the num
in the copy? What is confusing me is that if you type cout<<test.num<<endl
, of course it's wrong because you are trying to access the private num
, but if you pass the test by reference to the copy constructor, it works, can anybody tell me what is going on here?
推荐答案
私有成员是类本身的私有资源,而不是类的实例.
Private members are private to the class itself, not the instances of the class.
这篇关于与复制构造函数和私有成员的混淆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!