无论是java还是c++都提供了三种访问控制权限:
public、private、protected
它们提供类级别的访问控制,但是类的成员函数可以访问同一类的所有对象的所有私有成员,例如下面的C++示例:
#include "stdafx.h"
#include <stdlib.h>
class test
{
protected:
private:
int ivalue;
int _get_and_add()
{
return (ivalue + 10);
}
public:
test()
{
ivalue = 0;
}
void setValue(int _ivalue)
{
ivalue = _ivalue;
}
void setValue(test t)
{
ivalue = t.ivalue;
}
void add(test t)
{
ivalue += t._get_and_add();
}
int getValue()
{
return ivalue;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
test t1,t2;
printf("1. value:\n");
printf(" t1: %d \n",t1.getValue());
printf(" t2: %d \n",t2.getValue());
t2.setValue(100);
t1.setValue(t2);
printf("2.after setValue:\n");
printf(" t1: %d \n",t1.getValue());
printf(" t2: %d \n",t2.getValue());
t1.add(t2);
printf("3.after add_other:\n");
printf(" t1: %d \n",t1.getValue());
printf(" t2: %d \n",t2.getValue());
system("pause");
return 0;
}
其中类test的成员函数:
void setValue(test t)
{
ivalue = t.ivalue;
}
void add(test t)
{
ivalue += t._get_and_add();
}
分别访问了同类的其他对象(由参数传递过来)t 的私有数据成员 ivalue以及私有函数,上述程序的输出结果为: