C++ - 继承虚函数调用 代码
继承虚函数调用 代码
本文地址: http://blog..net/caroline_wendy
派生类继承基类时, 使用virtual时, 会进行动态绑定, 没有virtual关键字则会覆盖.
使用基类指针(Base*)指向派生类时, 调用函数, 则动态绑定的函数会调用派生类, 非动态绑定的函数调用基类.
代码:
/*
* main.cpp
*
* Created on: 2014.9.12
* Author: Spike
*/
/*eclipse cdt, gcc 4.8.1*/
#include <iostream>
using namespace std;
class Base {
public:
Base(int j) : i(j) {}
virtual ~Base() {}
void func1() {i*=10; func2();}
int getValue() {return i;}
protected:
virtual void func2() {i++;}
protected:
int i;
};
class Child : public Base {
public:
Child(int j) : Base(j) {}
void func1() {i*=100; func2();}
protected:
void func2() {i+=2;}
};
int main(void)
{
Base* pb = new Child(1);
pb->func1();
cout << pb->getValue() << endl;
return 0;
}
输出:
12
