C++ 实现类的封装时,有三种访问权限:
public:共有权限;可以被类外、类内、派生类对象访问;
private:私有权限;只能被类内和友元访问;
protected:保护权限;能被类内访问,派生类对象访问;
封装时的默认权限为private私有权限;
示例:
#include<iostream>
#include<assert.h>
using namespace std;
class A{
public:
int a;
A(){
a = 1;
b = 2;
c = 3;
d = 4;
}
void fun(){
cout << d << endl; //正确
cout << a << endl; //正确
cout << b << endl; //正确,类内访问
cout << c << endl; //正确,类内访问
}
public:
int a;
protected:
int b;
private:
int c;
};
int main(){
A itema;
itema.d = 10; //正确
itema.a = 20; //正确
itema.b = 30; //错误,类外不能访问protected成员
itema.c = 40; //错误,类外不能访问private成员
system("pause");
return 0;
}