繼承的語法:class 子類 : 繼承方式 父類
繼承降屬性權限,不可升屬性權限
繼承方式一共有三種:
-
公共繼承
-
保護繼承
-
私有繼承
#include <iostream>
#include <string>
using namespace std;class Base1
{
public:int m_A;
protected:int m_B;
private:int m_C;
};//公共繼承class Son1 : public Base1
{
public:void func() {m_A;// 可訪問public權限m_B;// 可訪問protected權限//m_C;// 不可訪問}
};void myClass() {Son1 s1;s1.m_A;//其他類只能訪問到公共權限;
}class Base2
{
public:int m_A;
protected:int m_B;
private:int m_C;
};class Son2 : protected Base2
{
public:void func() {m_A;// 可訪問protected權限m_B;// 可訪問protected權限//m_C;//不可訪問}
};void myClass2() {Son2 s;//s.m_A; //不可訪問
}//私有繼承
class Base3 {public:int m_A;
protected:int m_B;
private:int m_C;
};class Son3 : private Base3
{
public:void func() {m_A; //可訪問private權限m_B; //可訪問private權限//m_C; //不可訪問}
};class GrandSon3 : public Son3 {
public:void func() {//Son3是私有繼承,所以繼承Son3的屬性在GrandSon3中都無法訪問到//m_A;//m_B;//m_C;}
};int main() {system("pause");return 0;}