【发布时间】:2018-02-19 07:43:14
【问题描述】:
class IntVec
{
public:
IntVec();
IntVec(int siz);
IntVec(const IntVec& temp);
~IntVec();
private:
int* arr;
int size;
};
IntVec::IntVec()
{
size = 2;
arr = new int[size];
}
IntVec::IntVec(int siz)
{
size = siz;
arr = new int[size];
}
IntVec::IntVec(const IntVec& temp)
{
size = temp.size; // Why does this not cause an error? size is a private variable of object temp.
arr = new int[size];
for (int i = 0; i < size; i++)
{
arr[i] = temp.arr[i]; // Why doesn't this cause an error? arr is a private variable of object temp.
}
}
IntVec::~IntVec()
{
delete[] arr;
}
int main()
{
IntVec test1(2);
cout << test1.size; // Causes error (expected), since size is private.
}
我不清楚为什么我可以在复制构造函数中访问 temp 的 size 和 arr 变量,因为它们是私有变量。为什么我在 main() 中收到错误是有道理的,但我不确定为什么我在 Copy Constructor 中没有收到错误。
【问题讨论】:
-
size成员是 classIntVec的私有成员,并且复制构造函数也是该类的成员。 The access specifiers 是每个类,而不是每个对象。
标签: c++ class c++11 private copy-constructor