C 语言

关注公众号 jb51net

关闭
首页 > 软件编程 > C 语言 > C++继承和派生

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

作者:qq_24409999

这篇文章主要为大家详细介绍了C++继承和派生,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能够给你带来帮助

继承的写法

//父类 基类
class parent
{
};
//子类 派生类
//公有继承
class soon1:public parent
{
   public:
   protected:
};
//保护继承
class son2:protected parent
{
   public:
   protected:
};
//私有继承
class son3:private parent
{
    public:
    protected:
};
//继承和派生
//继承:子类中没有产生新的属性和行为
//派生:派生类中有新的属性和行为产生
class 子类名:继承方式 父类名
{
};
//继承方式  就是权限限定词

继承实质与权限问题 ​

 publicprotectedprivate
public继承publicprotected不可直接访问
protected继承protectedprotected不可直接访问
private继承privateprotected不可直接访问
#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;
}

总结

本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注脚本之家的更多内容! 

您可能感兴趣的文章:
阅读全文