请教一下关于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的,没有私有这么一说,以前看着没想什么,今天突然想到这个问题,为什么通过.运算符直接取到了私有数据呢?求指点!
The so-called class member access permissions
public/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 ishp.ps
, ps also belongs to HasPtr, which is completely consistent withprivate
regulations. This has nothing to do with arithmetic.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 ofHasPtr
. At this time, you can find the symbolhs.ps
. The compilation can pass, and then you can Go to private variables.PS:
js
There are also private variables. Can’t they be generated using closures?Access specifiers only work between different classes, not objects of the same class.