您的位置:首页 > 编程语言 > C语言/C++

c++中类中私有成员的调用?

2016-05-19 10:26 429 查看

Question

class A
{
private:
int x;
public:
A()
{
x = 90;
}
A(A a1, A a2)
{
a1.x = 10;
a2.x = 20;
}
int getX()
{
return this->x;
}
};


I know that code might be weird but I don’t understand why a1 and a2 can access private data member x?

answer

Good question. The point is that protection in C++ is class level, not object level. So a method being invoked on one object can access private members of any other instance of the same class.

This makes sense if you see the role of protection being to allow encapsulation to ensure that the writer of a class can build a cohesive class, and not have to protect against external code modifying object contents.

Another thought as to the real “why?”. Consider how you write almost any copy constructor; you want access to the original’s underlying data structure, not its presented interface.

转自

With a private modifier, why can the member in other objects be accessed directly?
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: