栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++ 多态(1)

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++ 多态(1)

#include 
#include 
#include 
using namespace std;

class Father{
public:
	string father_name;
	int father_age;
	
	Father(string name, int age);
	
    //在函数的声明处加上virtual表示该函数是一个虚函数,定义处可加可不加
	virtual void show_info(); 
};

Father::Father(string name, int age): father_name(name), father_age(age) {}
void Father::show_info() {
	std::cout << "父亲的名字是:" << father_name << "  年龄是:" << father_age << std::endl << std::endl;;
}

class Son:public Father{
public:
	string son_name;
	int son_age;
	
	Son(string father_name, int father_age, string name, int age);

	//子类中与父类中函数原型相同的成员函数前面的virtual可加可不加
	virtual void show_info(); 
};


int main(){
	
	Father* F = new Father("王刚", 50);
	F->show_info();
	
	F = new Son("李军", 60, "李小军", 35);//父类指针指向子类对象
	F->show_info();
	
	return 0;
}

Son::Son(string father_name, int father_age, string name, int age): Father(father_name, father_age), son_name(name), son_age(age) {}
void Son::show_info() {
	std::cout << "父亲的名字是:" << father_name << "  年龄是:" << father_age << std::endl;
	std::cout << "儿子的名字是:" << son_name << "  年龄是:" << son_age << std::endl;
}

加上虚函数构成多态之后的运行结果,达到了我们想要的效果:

如果不加虚函数,构不成多态,指向子类对象的父类指针F调用show_info之后,只访问到了子类的成员变量,但是访问不到子类的成员函数。结果如下:

 

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/937961.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号