假设我有以下课程:
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;
}
Run Code Online (Sandbox Code Playgroud)
将num
在副本应该是11
,我的问题是关于拷贝构造函数里面,我们为什么不能访问私有成员num
的test
使用num
来初始化num
的副本?令我困惑的是,如果你输入cout<<test.num<<endl
,当然这是错的,因为你试图访问私有num
,但如果你通过参考复制构造函数传递测试,它可以工作,任何人都可以告诉我这里发生了什么?
这是我第一次提问.我是外国人,所以解释我的问题有点难.也许我的标题也错了......让我们看看代码:
假设我已经定义了一个类:
class Test
{
public:
Test();
};
int main()
{
Test *pointer = new Test(); //what's the difference between these two ways,
Test test; //if the two ways are the same, which one is better under what
pointer = &test; //circumstance?
}
Run Code Online (Sandbox Code Playgroud)
我希望你们能理解我在说什么并帮助我.
c++ ×2