亲宝软件园·资讯

展开

C++继承和派生

qq_24409999 人气:0

继承的写法

//父类 基类
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;
}

总结

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

加载全部内容

相关教程
猜你喜欢
用户评论