【问题标题】:C++ - Why can a passed object's private variables be accessed directly in the Copy Constructor? [duplicate]C++ - 为什么可以在复制构造函数中直接访问传递的对象的私有变量? [复制]
【发布时间】: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 成员是 class IntVec 的私有成员,并且复制构造函数也是该类的成员。 The access specifiers 是每个类,而不是每个对象。

标签: c++ class c++11 private copy-constructor


【解决方案1】:

这是因为 public/protected/private 指的是类而不是单个对象。因此,一个类中的所有对象以及静态方法都可以访问彼此的内部。

【讨论】:

    【解决方案2】:
    size = temp.size; // Why does this not cause an error?  size is a private variable of object temp.
    

    您误解了访问规则。

    访问规则不适用于每个对象。

    它们适用于类型和函数。

    temp 的类型是IntVec。 IntVec 类型对象的任何成员都可以在IntVec 的任何成员函数中访问。

    非成员函数和其他类的成员函数将无法访问 IntVec 类型对象的 private 成员。

    【讨论】:

      【解决方案3】:

      这是因为access specifiers 是有效的per-class,而不是per-object。所以类方法可以访问类的任何实例的私有成员。

      类的所有成员(成员函数体、成员对象的初始化器和整个嵌套类定义)可以访问类可以访问的所有名称。 成员函数中的本地类可以访问该成员函数本身可以访问的所有名称。

      【讨论】:

        【解决方案4】:

        私有成员有类作用域意味着可以在类内部直接使用,不能直接在类外使用私有成员,因为拷贝构造函数在类内部,所以可以访问私有成员

        【讨论】:

          猜你喜欢
          • 2011-05-06
          • 2016-02-23
          • 2014-11-21
          • 2018-01-29
          • 2013-11-25
          • 2012-04-23
          • 1970-01-01
          • 2015-05-29
          相关资源
          最近更新 更多