C++类继承示例

发表于:2015-2-28 09:57

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:MindProbe    来源:51Testing软件测试网采编

  C++的子类与孙子类都实现了虚函数时,孙子类的实现会覆盖掉子类的实现。
  继承的最主要的应用就是把不同的类放到一个数组中,然后遍历调用同名函数。
  实例如下:
#include <iostream>
#include <stdlib.h>
#include <vector>
using namespace std;
class Parent{
protected:
string pname;
public:
Parent(string name){
pname=name;
}
virtual void printName(){};
};
class Child: public Parent{
protected:
string cname;
public:
Child(string name):Parent(name){
cname=name;
}
virtual void printName(){
cout<<"This is child, cname is "<<cname<<", pname is "<<pname<<endl;
}
};
class GrandChild: public Child{
private:
string gname;
public:
GrandChild(string name):Child(name){
gname=name;
}
virtual void printName(){
cout<<"This is grandchild, gname is "<<gname<<", cname is "<<cname<<", pname is "<<pname<<endl;
}
};
int main(){
string name="C";
Child child(name);
name="GC";
GrandChild gchild(name);
vector<Parent*> mlist;
mlist.push_back(dynamic_cast<Parent*>(&child));
mlist.push_back(dynamic_cast<Parent*>(&gchild));
for(int i=0;i<mlist.size();++i){
mlist[i]->printName();
}
}
  注意子类与孙子类的printName函数前的virtual可加可不加,都可以正确运行……
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号