没有人不辛苦,只是有人不喊疼。。。
---- 网易云热评
一、多继承,一个子类可以同时基类多个基类,这样的继承方式被称为多重继承。
#include <iostream>
using namespace std;
class Phone{//电话基类
public:
Phone(const string& num):m_num(num){}
void call(const string& num){
cout << m_num << "打给" << num <<endl;
}
private:
string m_num;
};
class Player{//播放器基类
public:
Player(const string& media)
:m_media(media){}
void play(const string& music){
cout << m_media << "播放器播放" <<
music << endl;
}
private:
string m_media;
};
class Computer{//计算机基类
public:
Computer(const string& os):m_os(os){}
void run(const string& app){
cout << "在" << m_os << "系统上运行"
<< app << endl;
}
private:
string m_os;
};
class SmartPhone:public Phone,public Player,
public Computer{//智能手机子类
public:
SmartPhone(const string& num,
const string& media,const string& os)
:Phone(num),Player(media),
Computer(os){}
};
int main(void)
{
SmartPhone iphone(
"13688886666","MP3","Android");
iphone.call("010-12315");
iphone.play("最炫小苹果");
iphone.run("Angry Bird");
SmartPhone* p1 = &iphone;
Phone* p2 = p1;
Player* p3 = p1;//+24
Computer* p4 = p1;//+48
cout << "p1=" << p1 << endl;
cout << "p2=" << p2 << endl;
cout << "p3=" << p3 << endl;
cout << "p4=" << p4 << endl;
cout << "sizeof(string)=" <<
sizeof(string) << endl;//24
return 0;
}
运行结果:
13688886666打给010-12315
MP3播放器播放最炫小苹果
在Android系统上运行Angry Bird
p1=009BFB68
p2=009BFB68
p3=009BFB84
p4=009BFBA0
sizeof(string)=28
二、多态
多态的语法特性除了要满足虚函数覆盖的条件,还必须通过指针或者通过引用调用虚函数,才能表现出来.
调用虚函数的指针也可以是成员函数中的this指针,当通过子类对象调用基类中成员函数,这时该成员函数中的this指针就是指向子类对象的基类指针,再通过它去调用虚函数同样可以表现多态的语法特性//重点掌握
#include <iostream>
using namespace std;
class Base{
public:
virtual int cal(int x,int y){
return x + y;
}
//void func(Base* this=&d)
void func(void){
//cout << this->cal(100,200) << endl;
cout << cal(100,200) << endl;//20000
}
};
class Derived:public Base{
public:
int cal(int x,int y){
return x * y;
}
};
int main(void)
{
Derived d;
Base b = d;
cout << b.cal(100,200) << endl;
d.func();//func(&d)
return 0;
}
运行结果:
300
20000
#include <iostream>
using namespace std;
class PDFParser{
public:
void parse(const char* pdffile){
cout << "解析出一个矩形" << endl;
onRect();
cout << "解析出一个圆形" << endl;
onCircle();
cout << "解析出一行文本" << endl;
onText();
}
private:
virtual void onRect(void) = 0;
virtual void onCircle(void) = 0;
virtual void onText(void) = 0;
};
class PDFRender:public PDFParser{
private:
void onRect(void){
cout << "绘制一个矩形" << endl;
}
void onCircle(void){
cout << "绘制一个圆形" << endl;
}
void onText(void){
cout << "显示一行文本" << endl;
}
};
int main(void)
{
PDFRender render;
render.parse("xx.pdf");
return 0;
}
运行结果:
解析出一个矩形
绘制一个矩形
解析出一个圆形
绘制一个圆形
解析出一行文本
显示一行文本
欢迎关注公众号:顺便编点程