描述你的问题
如下面的这段代码所示,为什么在Base这个类里面,它的拷贝函数,有个Base类的参数,为什么在拷贝函数里面,Base这个类的引用对象tmp,可以直接访问私有数据成员num,不是访问权限标志位private的,就只能被友元和成员函数访问吗?为什么可以直接在拷贝函数里面写tmp.num。这样的语句啊!如果放在main函数里面,声明一个Base类的对象,是不能访问私有数据成员的啊!
贴上相关代码
#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;
}
贴上报错信息
贴上相关截图
已经尝试过哪些方法仍然没解决(附上相关链接)
Of course your own members and their own functions can access
You said it yourself,,,
This
const Base& operator=(const Base& tmp)
function is a member function of the Base class. . .Members within a class can naturally be accessed, mainly to distinguish between classes and objects.
Personally, I think it can be understood this way: a class is its own friend class.
Specifically,
Base
a class is its own friend, and friends can access the private members of the class. In the copy assignment operator, a member of theBase
class, the type of thetmp
object isBase
, andBase
is a friend ofBase
, so you can access thetmp
class through theBase
object Private membersnum
, in the same way, can also implicitly accessthis
class private membersBase
through thenum
pointer.In addition, the return value of the copy assignment operator should generally not be a constantreference type.