Oct 11, 2010

对象可以访问同类对象的私有成员

The answer is that access control in C++ is done on an class by class basis, not on an instance-by-instance basis. Any instance of a class can access the private members of any other instance of the same class.


#include <iostream>

using namespace std;


class C
{
public:
C(int value):x(value) { }
int getHisX(const C &c) { return c.x; }
private:
int x;

/* data */
};

int main()
{
C c(3), d(4);
cout << c.getHisX(d) << endl;
return 0;
}

0 comments: