C++继承和派生

本文介绍了面向对象编程中的继承概念,包括公有、保护和私有继承的权限问题,以及构造函数在继承中的作用。同时,讨论了同名成员的处理规则和构造顺序。通过两个课后作业实例展示了继承的实际应用,包括单继承和多继承。
摘要由CSDN通过智能技术生成

目录

前言:

 继承方式与权限问题

继承中的构造函数

继承中同名问题

构造顺序问题


  • 前言:

继承:子类中没有产生新的属性或者行为

派生:子类中产生新的属性和行为

  •  继承方式与权限问题

  1. 公有继承
  2. 保护继承
  3. 私有继承

格式:

class 子类名:继承方式 父类名

{

};

class father//父类(基类)
{

public:
protected:
}
class son :public father//子类(派生类)公有继承
{
public:
protected:
}
  1. 继承方式就是权限限定词 
  2. 父类的私有属性和保护属性不能直接访问
  3. 私有继承会导致父类无法在孙子类产生任何作用
  • 继承中的构造函数

  1. 父亲的属性通过父类的构造函数初始化
  2. 子类中的构造函数必须要调用父类中的构造函数,必须采用初始化参数列表的形式
    class Kingdom{
    public:
    	Kingdom(string str, int data):name(str),age(data){}
    protected:
    	string name;
    	int age;
    };
    class UK:public Kingdom
    {
    public:
    	UK() :Kingdom("李傕",1){}
    
    protected:
    	
    };
  3. 单继承和多继承:
  • 单继承:只有一个父类
  • 多继承:两个或者两个以上的父

     4.一般不继承很多层,会导致类的臃肿

  • 继承中同名问题

     (就近原则)

  1. 数据成员同名:要想调用某个特定的类的数据成员,要用类名限定符号(::)
  2. 成员数函数同名
  3. 正常赋值调用
  4. 非正常赋值调用
  • 构造顺序问题

构造和继承顺序想同,析构相反,与初始化参数列表无关

课后作业1:

#include<iostream>
#include<string>
#define PI 3.14
using namespace std;
class shape{
public:
	float a,b,r;
	
	void print(){
		cout << "面积:" << a*b << "\t" << "周长:" << 2*a+2*b<< endl;
	}
	void printdata(){

		cout << "面积:" << PI*r*r << "\t" << "周长:" << 2 * PI*r << endl;
	}
protected:
	
};
class rect:public shape
{
public:

protected:
	
};
class circle:public shape
{
public:
protected:
};
int main(){
	rect r;
	circle c;
	cin >> r.a >> r.b >> c.r;
	r.print();
	c.printdata();
	while (1);
	return 0;
}

 课后作业2:

#include<iostream>
#include<string>
using namespace std;
class teacher{

public:



protected:


};
class master{

public:
	master() :name("张三"), age(25), grade(89), height(188), weight(123){}
	

protected:
	string name;
	int age;
	int grade;
	int height;
	int weight;

};

class student :public master,public teacher
{

public:
	
void print(){


		cout <<name << "\t" << age << "\t" << grade << "\t" << height << "\t" << weight << endl;
	}

protected:


};

int main(){

	student j;
	j.print();
	while (1);
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值