菱形继承与虚继承
#include <iostream>
using namespace std;
// 多继承与虚继承
class Furnature {
public:
int m;
}
// 将父亲类继承爷爷类的时候,改为虚继承,防止儿子在多继承我的时候,出现爷爷中的变量会考别多份
class Bed : virtual public Furnature{
public:
void sleep() {
cout << "在床上睡觉..." << endl;
}
};
class Sofa : virtual public Furnature {
public:
void sit() {
cout << "在沙发上休息..." << endl;
}
};
//沙发床
class SofaBed :public Bed, public Sofa {
public:
void sleepAndSit() {
sleep();
sit();
}
};
int main() {
SofaBed sb;
sb.sleepAndSit();
sb.m = 300;
return 0;
}
image.png
虚函数的应用场景
问题引出
#include <iostream>
using namespace std;
class Human {
public:
double age;
Human() {
age = 33;
}
//void say() {
virtual void say() {
cout << "human :" << age << endl;
}
};
class Student : public Human {
public:
void say() override{
cout << "Student :" << age << endl;
}
};
void sayEx(Human * p) {
p->say();
}
int main() {
Student * s1 = new Student();
Human * h1 = new Human();
// 明明给了Student类型的指针,确调用的父类方法,解决:将父类中的say方法实现为虚方法
sayEx(s1); // human :33
delete s1;
delete h1;
return 0;
}
纯虚函数
纯虚函数定义
class <类名>
{
virtual <类型><函数名>(<参数表>)=0;
};
在基类中不能对虚函数给出有意义的实现,而把它声明为纯虚函数,它的实现留给该基类的派生类去做。这就是纯虚函数的作用
#include <iostream>
using namespace std;
class Printable {
public:
virtual void ClassName() = 0;
};
class Human : public Printable{
public:
double age;
Human() {
age = 33;
}
virtual void say() {
cout << "Human :" << age << endl;
}
void ClassName() {
cout << "Human ..." << endl;
}
};
class Student : public Human {
public:
void say() override{
cout << "Student :" << age << endl;
}
void ClassName() {
cout << "Student ..." << endl;
}
};
void print(Printable * p) {
p->ClassName();
}
int main() {
Student * s1 = new Student();
Human * h1 = new Human();
print(s1); //Student ...
print(h1); // Human ...
delete s1;
delete h1;
return 0;
}
网友评论