请教一下关于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的,没有私有这么一说,以前看着没想什么,今天突然想到这个问题,为什么通过.运算符直接取到了私有数据呢?求指点!
所谓的类成员访问权限
public/protected/private
是针对来自外部的访问而言的,你这是类自身的函数,都是自家人能有什么问题。或者这么说,调用方是
HasPtr::operator =
,是归属于HasPtr的;而被调用方是hp.ps
,ps也是归属于HasPtr,完全符合private
的规定。这和.运算没啥关系。