派生类中的虚函数

Base.h

#pragma once
#include <iostream>
class Base
{
public:
	Base(int b = 0):b_(b) {}
	virtual Base* clone()const {std::cout << __FUNCSIG__<<std::endl; return new Base(*this);}
	virtual int get_value() const {std::cout << __FUNCSIG__<<std::endl;return b_;}
private:
	int b_;
};
Derive.h

#pragma once
#include <iostream>
class Derive :public Base
{
public:
	Derive(int d = 0):d_(d) {}
	virtual int get_value() const {std::cout << __FUNCSIG__<<std::endl; return d_;}
private:
	int d_ ;
};
main.cpp

#include <iostream>
#include "Base.h"
#include "Derive.h"
using namespace std;
int main(int __argc, const char** __argv)
{
	Base* p = new Derive(3);
	cout <<"p->get_value():"<< p->get_value() << endl;

	Base* pCopy = p->clone();
	cout << "pCopy->get_value():"<<pCopy->get_value() << endl;

	delete p;
	delete pCopy;
	return EXIT_SUCCESS;
}
运行结果:

int __thiscall Derive::get_value(void) const
p->get_value():3
class Base *__thiscall Base::clone(void) const
int __thiscall Base::get_value(void) const
pCopy->get_value():0
请按任意键继续. . .
p->get_value()调用的是Derive::get_value(void) const, pCopy->get_value()调用的却是基类的Base::get_value(void)const,输出的结果:0,这显然是不对的。
因为派生类没有覆盖基类的virtual void clone() ,则派生类直接继承其在基类的版本,
即在Derive类中,没有用Derive::clone()方法,覆盖Base::clone(),直接把Base::clone()方法继承过来,
以至于pCopy->clone()时,调用了Base::clone(),Base::clone只克隆Derive类的Base部分,返回了Base*,
而不是Derive*,所以pCopy->get_value(),调用了Base::get_value(),
在p = new Derive()时,调用Derive::Derive(int d = 0)又调用了Base::Base(int b = 0)构造函数,使b_(0),
在Base::clone()中,new Base(*this)又调用了Base::Base(const Base&)构造了一个副本,赋值给pCopy
最后 pCopy->get_value(),调用了;Base::get_value()输出了 0(可以改动Base(int b = 1),看看pCopy->get_value()输出结果是不是变化了)
现在让我们动起手来, 在Derive类中覆盖clone()

#pragma once
#include <iostream>
class Derive :public Base
{
public:
	Derive(int d = 0):d_(d) {}
	virtual int get_value() const {std::cout << __FUNCSIG__<<std::endl; return d_;}
	virtual Derive* clone()const {std::cout << __FUNCSIG__<<std::endl;return new Derive(*this);}
private:
	int d_ ;
};

运行结果:

int __thiscall Derive::get_value(void) const
p->get_value():3
class Derive *__thiscall Derive::clone(void) const
int __thiscall Derive::get_value(void) const
pCopy->get_value():3
请按任意键继续. . .
看,结果为 3 了吧!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值