当前位置:主页 > 软件编程 > C代码 >

C++的继承和派生你了解吗

时间:2022-11-17 10:14:50 | 栏目: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;
}

总结

您可能感兴趣的文章:

相关文章