virtual的基础知识

【参考链接】

https://www.cnblogs.com/weiyouqing/p/7544988.html

什么是虚函数:

虚函数是指一个类中你希望重载的成员函数 ,当你用一个  基类指针或引用   指向一个继承类对象的时候,调用一个虚函数时, 实际调用的是继承类的版本。  ——摘自MSDN

虚函数最关键的特点是“动态联编”,它可以在运行时判断指针指向的对象,并自动调用相应的函数。

一定要注意“静态联编 ”和“ 动态联编 ”的区别。

【参考代码】

#include <iostream>
//#include <conio.h> //getch() isn't a standard lib function
//#include <curses.h> //g++ virtual.cpp -lncurses -std=c++11
#include <stdio.h>

using namespace std;

class Parent
{
public:
char data[20];
void Function1() { printf("This is parent,function1 "); }
virtual void Function2(); // 这里声明Function2是虚函数
}parent;

void Parent::Function2(){
printf("This is parent,function2 ");
}

class Child:public Parent
{
void Function1() { printf("This is child,function1 "); }
void Function2();

}child;

void Child::Function2() {
printf("This is child,function2 ");
}

typedef Parent* pParent;

int main(int argc, char* argv[])
{
pParent p1; // 定义一个基类指针

char ch[] = "hello world";
printf("%s ", ch);

if (getchar() == 'c') // 如果输入一个小写字母c
p1=&child;    // 指向继承类对象
else
p1=&parent; // 否则指向基类对象

p1->Function1(); // 这里在编译时会直接给出Parent::Function1()的入口地址。
p1->Function2(); // 注意这里,执行的是哪一个Function2
return 0;
}

原文地址:https://www.cnblogs.com/atoman/p/11947667.html