search

Home  >  Q&A  >  body text

c++构造函数的问题

请教一下关于c++中构造函数的问题:

class HasPtr {
public:
    HasPtr(const std::string& s = std::string()) : ps(new std::string(s)), i(0)
    {
    }
    HasPtr(const HasPtr& hp) : ps(new std::string(*hp.ps)), i(hp.i) {}
    HasPtr& operator=(const HasPtr& hp)
    {
        std::string* new_ps = new std::string(*hp.ps);
        delete ps;
        ps = new_ps;
        i = hp.i;
        return *this;
    }

private:
    std::string* ps;
    int i;
};

想请问一下为什么在拷贝构造函数和赋值操作符中,接受的那个引用可以直接用hs.ps来取它的私有数据ps,之前都是写js的,没有私有这么一说,以前看着没想什么,今天突然想到这个问题,为什么通过.运算符直接取到了私有数据呢?求指点!

怪我咯怪我咯2773 days ago348

reply all(3)I'll reply

  • 巴扎黑

    巴扎黑2017-04-17 14:20:34

    The so-called class member access permissionspublic/protected/private are for access from the outside. This is a function of the class itself, so you can have any problems with it.

    In other words, the caller is HasPtr::operator = and belongs to HasPtr; while the callee is hp.ps, ps also belongs to HasPtr, which is completely consistent with private regulations. This has nothing to do with arithmetic.

    reply
    0
  • 怪我咯

    怪我咯2017-04-17 14:20:34

    The member functions of a class can access the private properties of the instance object of the class. The access rights of the class are imposed by the compiler, so as long as there are no problems during the compilation stage, there is no problem. Private variables can be obtained during the running process. Yes, the stage that determines whether private variables can be accessed is the compilation stage. In the compilation stage, hs is in the class scope of HasPtr. At this time, you can find the symbol hs.ps. The compilation can pass, and then you can Go to private variables.
    PS: jsThere are also private variables. Can’t they be generated using closures?

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-17 14:20:34

    Access specifiers only work between different classes, not objects of the same class.

    reply
    0
  • Cancelreply