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的大小和arr变量,因为它们是私有变量。为什么在main()中出现错误是有道理的,但是我不确定为什么在复制构造函数中没有出错。
这是因为访问说明符对每个类有效,而不对每个对象有效。因此,类方法可以访问该类任何实例的私有成员。
类的所有成员(成员函数的主体,成员对象的初始化程序以及整个嵌套的类定义)都可以访问类可以访问的所有名称。成员函数中的本地类可以访问成员函数本身可以访问的所有名称。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句