描述你的问题
如下面的这段代码所示,为什么在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;
}
贴上报错信息
贴上相关截图
已经尝试过哪些方法仍然没解决(附上相关链接)
大家讲道理2017-04-17 13:26:42
You said it yourself,,,
If the access permission flag is private, it can only be accessed by friends and member functions
This const Base& operator=(const Base& tmp)
function is a member function of the Base class. . .
PHPz2017-04-17 13:26:42
Members within a class can naturally be accessed, mainly to distinguish between classes and objects.
巴扎黑2017-04-17 13:26:42
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 the Base
class, the type of the tmp
object is Base
, and Base
is a friend of Base
, so you can access the tmp
class through the Base
object Private members num
, in the same way, can also implicitly access this
class private members Base
through the num
pointer.
In addition, the return value of the copy assignment operator should generally not be a constantreference type.