// xuhanshu_example.cpp : 定义控制台应用程序的入口点。
//虚函数,可以让基类使用派生类的函数
#include "stdafx.h"
#include <iostream>
using namespace std;
//基类
class People{
public:
People(char *name, int age);
virtual void display(); //声明为虚函数
protected:
char *m_name;
int m_age;
};
People::People(char *name, int age) :m_name(name), m_age(age)
{
}
void People::display()
{
cout << m_name << "今年" << m_age << "岁了,是个无业游民。" << endl;
}
//派生类
class Teacher :People{
public:
Teacher(char *name, int age, int salary);
virtual void display(); //声明为虚函数
private:
int m_salary;
};
Teacher::Teacher(char *name, int age, int salary):People(name, age), m_salary(salary)
{
}
void Teacher::display() //声明为虚函数
{
cout << m_name << "今年" << m_age << "岁了,是一名教师,每月有" << m_salary << "元的收入。" << endl;
}
int _tmain(int argc, _TCHAR* argv[])
{
Peopl
C++:虚函数,用于继承
最新推荐文章于 2021-09-02 15:01:27 发布
本文详细探讨了C++中的虚函数机制及其在继承系统中的作用。通过实例解析,展示了虚函数如何实现多态性,以及在子类重写父类方法时如何确保正确调用。同时,还讨论了虚函数在动态绑定过程中的关键角色。
摘要由CSDN通过智能技术生成