1、运用指针的一些问题
1、基类指针操作派生类对象数组----->基类和派生类的步长不一致
2、虚析构函数:—>通过基类指针释放派生类对象:解决办法,将基类的析构函数设置成虚函数
#include <iostream>
using namespace std;
class Animal
{
public:
Animal()
{
cout << "Animal 构造函数" << endl;
}
virtual ~Animal() //防止用基类指针操作派生类空间后没有释放派生类开辟的地址空间,造成内存泄漏
{
cout << "Animal 析构函数" << endl;
}
virtual void sleep()
{
cout << "动物睡觉" <<endl;
}
void eat()
{
cout << "动物吃饭" <<endl;
}
protected:
int a;
};
class Dog : public Animal
{
public:
Dog()
{
cout << "Dog 构造函数" << endl;
}
~Dog()
{
cout << "Dog 析构函数" << endl;
}
void sleep()
{
cout << "狗 趴着睡觉" <<endl;
}
void eat()
{
cout << "狗 啃骨头" <<endl;
}
protected:
int b;
};
//1、基类指针操作派生类对象数组----->基类和派生类的步长不一致
int main1()
{
Dog d[10];
Dog *pd = d;
for(int i = 0;i< 10;i++)
pd[i].sleep();
Animal *pa = d; //发生段错误
for(int i = 0;i< 10;i++)
pa[i].sleep();
return 0;
}
//2、虚析构函数:--->通过基类指针释放派生类对象
int main()
{
Animal *pa = new Dog;
delete pa;
return 0;
}
2、纯虚函数
1、用于处理一些抽象的事物,例如图形…
2、 纯虚函数 : 虚函数,只需要声明,不需要实现, 将函数定义换成 = 0;
3、 抽象类: 拥有纯虚函数的类
(1、抽象类不能实例化对象 —> 不能创建变量
( 2、派生类必须实现全部的纯虚函数,如果不全部实现,则派生类将变为抽象类
( 3、抽象类可以定义指针,用来操作派生类对象
#include <iostream>
using namespace std;
// 纯虚函数 : 虚函数,只需要声明,不需要实现, 将函数定义换成 = 0;
// 抽象类: 拥有纯虚函数的类
// 1、抽象类不能实例化对象 ---> 不能创建变量
// 2、派生类必须实现全部的纯虚函数,如果不全部实现,则派生类将变为抽象类
// 3、抽象类可以定义指针,用来操作派生类对象
class Sharp
{
public:
virtual double getS() = 0; // 获取面积
// virtual double getC() = 0; // 获取周长
};
class Circle : public Sharp
{
public:
Circle(int r)
{
this->r = r;
}
virtual double getS()
{
return 3.14*r*r;
}
private:
int r;
};
class Rectangle : public Sharp
{
public:
Rectangle(int a, int b)
{
this->a = a;
this->b = b;
}
virtual double getS()
{
return a*b;
}
private:
int a; // 长
int b; // 宽
};
void func(Sharp *ps)
{
cout << ps->getS() << endl; // 多态
}
int main()
{
Circle *pc = new Circle(2);
Rectangle *pr = new Rectangle(1,2);
// Sharp s;
// s.getS();
func(pc);
func(pr);
delete pc;
delete pr;
return 0;
}
3、接口
#include <iostream>
using namespace std;
// C++模拟接口:类中只有纯虚函数,没有变量
// 不建议使用多继承,但是可以继承多个接口
// 加法
class Add
{
public:
virtual void add() = 0;
virtual void show() = 0;
};
// 乘法
class Mul
{
public:
virtual void mul() = 0;
virtual void show() = 0;
};
class Num : public Add, public Mul
{
public:
Num (int a, int b)
{
this->a = a;
this->b = b;
}
virtual void add()
{
res = a + b;
}
virtual void mul()
{
res = a * b;
}
virtual void show()
{
cout << "res = " << res << endl;
}
private:
int a;
int b;
int res;
};
int main()
{
Num num(2,3);
Add *pa = #
pa->add();
pa->show();
Mul *pm = #
pm->mul();
pm->show();
return 0;
}