C++ 虚函数,纯虚函数,抽象类整理
原创
©著作权归作者所有:来自51CTO博客作者DT陶喆的原创作品,请联系作者获取转载授权,否则将追究法律责任
- 抽象类,类中包含纯虚函数的为抽象类,其中抽象类的子类必须实现抽象类的纯虚函数方法。
- 抽象类无法实例化
- 虚函数,子类可以实现或者不实现该方法都可以
- 如果父类调用子类的基类指针时,有虚函数的则使用子类的实现虚函数的类。
具体实例代码:
头文件:
#include "stdafx.h"
class People{
public:
virtual bool getOpenSex() = 0;
virtual void setHeight(int height); //设置身高
virtual void setWeight(int weight);//设置体重
private:
int m_height;
int m_weight;
};
class Man:public People
{
public:
//virtual void setHeight(int height);
bool getOpenSex(); //true:man false:woman
private:
int sex_attr; //sex-attribute
};
class WoMan:public People
{
public:
//virtual void setHeight(int height);
bool getOpenSex(); //true:man false:woman
private:
int sex_attr; //sex-attribute
};
class Baby{
public:
virtual void BabyFace(); //虚函数默认调用子函数方法
};
class AngleBaby:public Baby
{
public:
virtual void BabyFace();
};
实现文件:
// AbstractClassDemo.cpp : 定义控制台应用程序的入口点。
// C++ 抽象类使用:
// 抽象类:即类中包含纯虚函数,抽象类不能被实例化
#include "stdafx.h"
#include "PeopleDemo.h"
using namespace std;
void People::setHeight(int height)
{
cout << "I want to say nothing height!" << endl;
m_height = height;
}
void People::setWeight(int weight)
{
cout << "I want to say nothing!" << endl;
m_weight = weight;
}
bool Man::getOpenSex()
{
cout << "It is a man!" << endl;
return true;
}
bool WoMan::getOpenSex()
{
cout << "It is a woman!" << endl;
return true;
}
void Baby::BabyFace()
{
cout << "You are a baby!" << endl;
}
void AngleBaby::BabyFace(){
cout << "You are Angle Baby!" << endl;
}
//void Man::setHeight(int height)
//{
// cout << "man height" << endl;
// return ;
//}
//void WoMan::setHeight(int height)
//{
// cout << "woman height" << endl;
// return ;
//}
int _tmain(int argc, _TCHAR* argv[])
{
Man xx;
xx.setHeight(111);
xx.getOpenSex();
WoMan *ss = new WoMan();
ss->getOpenSex();
ss->setHeight(1113);
delete ss;
Baby * mybaby = new AngleBaby();
mybaby->BabyFace();
system("pause");
return 0;
}
运行结果: