(一)访问控制和继承
公有继承(public):当一个类派生自公有基类时,基类的公有成员也是派生类的公有成员,基类的保护成员也是派生类的保护成员,基类的私有成员不能直接被派生类访问,但是可以通过调用基类的公有和保护成员来访问。
保护继承(protected): 当一个类派生自保护基类时,基类的公有和保护成员将成为派生类的保护成员。
私有继承(private):当一个类派生自私有基类时,基类的公有和保护成员将成为派生类的私有成员。
访问权限总结出不同的访问类型,如下所示:
(二)使用示例
- 在同一个类中都可以使用
#include <iostream>
using namespace std;
class test{
public:
int test1;
private:
int test2;
protected:
int test3;
void A(void)
{
test1 = 0;
test2 = 0; /*error*/
test3 = 0;
}
};
int main(int argc, char **argv)
{
}
- 在派生类中不能访问private中的
#include <iostream>
using namespace std;
class test{
public:
int test1;
private:
int test2;
protected:
int test3;
};
class Rectangle:public test{
public:
void A(void)
{
test1 = 0;
// test2 = 0; /*error*/
test3 = 0;
}
};
int main(int argc, char **argv)
{
}
运行结果,注销掉就能编译成功了
- 外部的类使用
#include <iostream>
using namespace std;
class test{
public:
int test1;
private:
int test2;
protected:
int test3;
};
int main(int argc, char **argv)
{
test S;
S.test1 = 0;
//S.test2 = 0; /*error*/
//S.test3 = 0; /*error*/
}
运行结果,外部类无法使用protected和private,注销掉就成功了