第8节 C++继承和派生
继承方式与权限问题
继承的写法
//父类 基类
class parent
{
};
//子类 派生类
//公有继承
class soon1:public parent
{
public:
protected:
};
//保护继承
class son2:protected parent
{
public:
protected:
};
//私有继承
class son3:private parent
{
public:
protected:
};
//继承和派生
//继承:子类中没有产生新的属性和行为
//派生:派生类中有新的属性和行为产生
class 子类名:继承方式 父类名
{
};
//继承方式 就是权限限定词
继承实质与权限问题
- ? 继承的实质:父类的数据和成员子类中有一份
- ? 权限问题:继承方式只会增强父类属性在子类中的权限显示
| public | protected | private |
---|
public继承 | public | protected | 不可直接访问 | protected继承 | protected | protected | 不可直接访问 | private继承 | private | protected | 不可直接访问 |
#include<iostream>
#include<string>
using namespace std;
class parent
{
public:
void print()
{
cout << name << "\t" << money << endl;
}
string& getWide()
{
return wide;
}
protected:
string name;
int money;
private:
string wife;
};
//子类
class son :public parent
{
public:
void printSon()
{
print();
cout << name<<"\t"<<money<< endl;
//cout << wife << endl;父类中的私有属性不能直接访问
cout << getWide() <<endl;//间接通过父类的函数访问
}
protected:
};
class A
{
public:
int a1;
protected:
int a2;
private:
int a3;
};
class B :public A
{
public:
//int a1;
protected:
//int a2;
private:
//int a3;不能直接访问
};
class C :protected A
{
public:
protected:
//int a1; public 显示protected
//int a2;
private:
//int a3;不能直接访问
};
class D :private A
{
public:
void print()
{
cout << a1 << endl;;
cout << a2<< endl;
}
protected:
private:
//int a1; public 显示protected
//int a2;
//int a3;//父类的私有属性不能直接访问
};
//私有继承会导致当前父类 无法在孙子类有任何作用
class F :public D
{
public:
};
int main()
{
son boy;
boy.printSon();
B b;
b.a1 = 123;
C c;
//c.a1 = 12;
return 0;
}
|