search

Home  >  Q&A  >  body text

c++中的访问权限的问题

  1. 描述你的问题
    为什么下面的这段代码里面,类的拷贝函数中的参数,是Base类的一个引用,Base类声明有一个私有的数据成员num,为什么拷贝函数中,x可以直接访问x的私有数据成员num。如果在main函数里面声明一个Base 类的对象,如Base test; 不可能直接test.num调用这个数据成员啊?为什么在类里面却又可以啊?

  2. 贴上相关代码

    `#include <iostream>

    class Base
    {
    private:

       int num;

    public:

       Base(int tmp = 0) : num(tmp) {}
       const Base& operator=(const Base& tmp)
       {
           num = tmp.num;
           return *this;
       } 

    };

    int main()
    {

       return 0;

    }`

  3. 贴上报错信息

  4. 贴上相关截图

  5. 已经尝试过哪些方法仍然没解决(附上相关链接)

PHPzPHPz2885 days ago584

reply all(2)I'll reply

  • 巴扎黑

    巴扎黑2017-04-17 13:26:16

    You can think of this as a special case of the agreement: the copy constructor belongs to the member function of this class, and it can also be understood if it can access the private members of the parameter object.

    In terms of language design, any design can be done. But if it is designed to be inaccessible, then the internal members must be exposed (the members are public or provide a get function), which is not a good choice.

    reply
    0
  • 巴扎黑

    巴扎黑2017-04-17 13:26:16

    Because access permissions are at the class level, not at the object level

    The calling object of the copied function and the object of the copied function parameters can still access the private functions between them

    reply
    0
  • Cancelreply