C++继承

多继承:一个子类多个父类
多重继承:子类当父类

基类成员访问属性继承方式派生类成员访问属性
private成员public无法访问
protected成员publicprotected
public成员publicpublic
基类成员访问属性继承方式派生类成员访问属性
private成员protected无法访问
protected成员protectedprotected
public成员protectedprotected
基类成员访问属性继承方式派生类成员访问属性
private成员private无法访问
protected成员privateprivate
public成员privateprivate

菱形继承解决采用宏定义
#ifndef PERSON_H
#define PERSON_H
……
#endif
菱形继承实例

#include<iostream>
#include<stdlib.h>
#include<string>
using namesoace std;
/**定义人类:Person*/
class Person
{
public:
	Person()
	{
	cout<<Person""<<endl;
	}
	~Person()
	{
	cout<<"~Person"<<endl;
	}
	void eat()
	{
	cout<<"eat"<<endl;
	}
};
/**
*定义工人类:Worker
*虚继承人类
*/
class Worker:virtual public Person
{
public:
	Worker(string name)
	{
		m_strName=name;
		cout<<"Worker"<<endl;
	}
	~Worker()
	{
		cout<<"~Worker<<endl;
	}
	void work()
	{
		cout<<m_strName<<endl;
		cout<<"work"<<endl;
	}
protected:
	string m_strName;
	};
/**
*定义儿童类Children
*虚继承人类
*/
class Children:virtual public Person
{
public:
	Children(int age)
	{
		m_iAge = age;
		cout<<"Children"<<endl;
	}
	~Children()
	{
	cout<<"~Children"<<endl;
	}
	void play()
	{
		cout<<m_iAge<<endl;
		cout<<"play"<<endl;
	}
protected:
	int m_iAge;
};
/**
*定义童工类:ChildLabourer
*公有继承工人类和儿童类
*/
class ChildLabourer:public Worker,public Children
{
public:
	childLabourer(string name,int age):Worker(name),Children(age)
	{
		cout<<"ChildLabourer"<<endl;
	}
	~ChildLabourer()
	{
		cout<<"~ChildLabourer"<<endl;
	}
};
int main()
{
	///用new关键字实例化童工类对象
	ChildLabourer *p=new ChildLabourer("jim",14);
	//调用童工类对象各方法。
	p->eat();
	p->work();
	p->play();
	delete p;
	p=NULL;
	return 0;
}

RTTI
RTTI(Run-Time Type Identification),通过运行时类型信息程序能够使用基类的指针或引用来检查这些指针或引用所指的对象的实际派生类型

实例

函数模板

#include <iostream>
using namespace std;
template <typename T>
void swapNum(T &a,T &b)
{
T temp = a;
a = b;
b = temp;
}
int main(void)
{
int x = 10;
int y = 20;
swapNum<int>(x,y);
cout << "x = " << x << endl;
cout << "y = " << y << endl;
return 0;
}

类模板:

#include<iostream>
using namespace std;
/**
*定义一个矩形类模板Rect
*成员函数:calcArea()、calePerimeter()
*数据成员:m_length、m_height
*/
template <typename T>
class Rect
{
public:
	Rect(T length,T height);
	T calcArea();
	T calePerimeter();
public:
	T m_length;
	T m_height;
};
/**
*类属性
*/
template <typename T>
Rect<T>::Rect(T length,T height)
{
	m_length=length;
	m_height=height;
}
/**
*面积方法实现
*/
template <typename T>
T Rect<T>::clacArea()
{
	return m_length*m_height;
}
/**
*周长方法实现
*/
template <typename T>
T Rect<T>::claePerimeter()
{
	return(m_length+m_height)*2;
}
int main(void)
{
	Rect<int>rect(3,6);
	cout<<rect.calcArea()<<endl;
	cout<<rect.calePerimeter()<<endl;
	return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值