C++ Virtual关键字实现动态绑定


    C++中的动态绑定,是通过Virtual关键字来指定为虚函数,通过基类指针或引用调用。

    示例代码:

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;

//学习Virtual,了解通过Virtual实现动态绑定
class Zone{

public:
	Zone(){
		cout << "construct a zone" << endl;
	}

  virtual void func(){
		cout << "I'm a zone" << endl;
	}

~Zone(){
		cout << "destruct Zone" << endl;
	}
};

class Country : public Zone{

public:
	Country(){
		cout << "construct a country" << endl;
	}

	void func(){
		cout << " i'm a country" << endl;
	}

	~Country(){
		cout << "destruct country" << endl;
	}
};

class China : public Country{

public:
	China(){
		cout << "Construct China" << endl;
	}

	void func(){
		cout << "I'm China" << endl;
	}

	~China(){
		cout << "destruct China" << endl;
	}
};

int main()
{
	FILE* fp = freopen("D:\mylog.txt","w",stdout);
	if(NULL == fp) return -1;
	Zone* c = new China;
	c->func();
	delete c;
	fclose(fp);
	return 0;
}
输出:
        construct a zone
construct a country
Construct China
I'm China
destruct Zone

从Log中看到,通过Zone基类指针,指向China子类,调用的是子类的func方法,而不是基类的。

而析构函数只调用了基类的,未调用子类的。

修改方式为在Zone析构函数前加Virtual即可。

打印结果:

construct a zone
construct a country
Construct China
I'm China
destruct China
destruct country
destruct Zone


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值