多继承:一个子类多个父类
多重继承:子类当父类
基类成员访问属性 | 继承方式 | 派生类成员访问属性 |
---|---|---|
private成员 | public | 无法访问 |
protected成员 | public | protected |
public成员 | public | public |
基类成员访问属性 | 继承方式 | 派生类成员访问属性 |
---|---|---|
private成员 | protected | 无法访问 |
protected成员 | protected | protected |
public成员 | protected | protected |
基类成员访问属性 | 继承方式 | 派生类成员访问属性 |
---|---|---|
private成员 | private | 无法访问 |
protected成员 | private | private |
public成员 | private | private |
菱形继承解决采用宏定义
#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;
}