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 了吧!