#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
using namespace std;
//知识点1
//动态联编和静态联编
class Animal {
public:
// 在父类上声明一个虚函数
virtual void speak() {
cout << "动物在说话" << endl;
}
};
class Cat :public Animal {
public:
void speak() {
cout << "小猫在说话" << endl;
}
};
// 动态联编
// 将dospeak方法改为虚函数,在父类上声明一个虚函数,虚函数发生了多态
// 父类的引用或者指针指向子类对象
void dospeak(Animal& animal)
{
animal.speak();
}
// 如果发生了继承,编译器允许类型转换
void test1() {
Cat cat;
dospeak(cat);
}
void test2() {
//父类的指针指向了子类对象,发生了多态
Animal* animal = new Cat;
}
// 知识点2
// 利用多态实现计算器
// 计算机的基类
class Caculator {
public:
void setval1(int a) {
this->val1 = a;
}
void setval2(int b) {
this->val2 = b;
}
int getval1() {
return this->val1;
}
int getval2() {
return this->val2;
}
// 虚函数
//virtual int getResult() { return 0; }
// 纯虚函数
// 如果父类中有了纯虚函数 子类继承父类,就必须实现纯虚函数
// 如果父类中有了纯虚函数,这个父类就无法实例化对象
// 如果父类中有了纯虚函数,这个类又称为抽象类
virtual int getResult() = 0;
private:
int val1;
int val2;
};
// 加法计算器
class plusCaculator :public Caculator {
public:
virtual int getResult() {
return this->getval1() + this->getval2();
}
};
// 减法法计算器
class subCaculator :public Caculator {
public:
virtual int getResult() {
return this->getval1() - this->getval2();
}
};
// 乘法法计算器
class MulCaculator :public Caculator {
public:
virtual int getResult() {
return this->getval1() * this->getval2();
}
};
void test3() {
// Caculator * c1 = new plusCaculator;
// Caculator* c1 = new subCaculator;
Caculator* c1 = new MulCaculator;
c1->setval1(10);
c1->setval2(20);
cout << c1->getResult() << endl;
delete c1;
}
// 知识点3
// 虚析构和纯虚析构
class Animal1 {
public:
virtual void speak() {
cout << "动物在说话" << endl;
}
// 普通析构 是不会调用子类的析构,所以可能会导致释放不干净
/*
~Animal1() {
cout << "Animal1的析构函数调用" << endl;
}
*/
//利用虚析构来解决这个问题
/*
virtual ~Animal() {
cout << "Animal的析构函数调用" << endl;
}
*/
// 纯虚析构
// 纯虚析构,需要声明,还需要实现,类外实现
// 如果函数中出现了纯虚析构函数,那么这个类也算抽象类
// 抽象类不能被实例化
virtual ~Animal1() = 0;
};
Animal1::~Animal1() {
//纯虚析构函数的实现
cout << "Animal的纯虚析构的实现" << endl;
}
class Cat1 :public Animal1 {
public:
Cat1(const char* name) {
this->m_Name = new char[strlen(name) + 1];
strcpy(this->m_Name, name);
}
virtual void speak() {
cout << "小猫在说话" << endl;
}
~Cat1() {
cout << "Cat1的析构调用了" << endl;
if (this->m_Name != NULL) {
delete[] this->m_Name;
this->m_Name = NULL;
}
}
char* m_Name;
};
void test4() {
Animal1* animal = new Cat1("Tom");
animal->speak();
delete animal;
}
int main() {
test1();
test3();
test4();
system("pause");
return EXIT_SUCCESS;
}