派生C ++类如何通过基指针来克隆本身? [英] How can a derived C++ class clone itself via a base pointer?

查看:254
本文介绍了派生C ++类如何通过基指针来克隆本身?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我想要做的(这段代码不工作):

  class Base 
{
virtual Base * clone(){return new Base(this); }
virtual void ID(){printf(BASE);
};

class Derived:publc Base
{
virtual Base * clone(){return new Derived(this); }
virtual void ID(){printf(DERIVED); }
}



派生d;
Base * bp =& d;
Base * bp2 = bp-> clone();

bp2-> ID();

我会像是看到DERIVED打印出来。我得到的是BASE。我是一个长期的C程序员,相当有经验的C ++ ...但我没有任何进展与这一个...任何帮助将不胜感激。

解决方案

一旦所有的编译错误都修复了,我最终得到:

  #include< cstdio> 

class Base
{
public:
Base(){}
Base(const Base&){}
virtual Base * clone (){return new Base(* this); }
virtual void ID(){printf(BASE); }
};

class Derived:public Base
{
public:
Derived(){}
Derived(const Derived&){}
virtual Base * clone(){return new Derived(* this); }
virtual void ID(){printf(DERIVED); }
};


int main()
{
Derived d;
Base * bp =& d;
Base * bp2 = bp-> clone();

bp2-> ID();
}

这就给你你想要的 - DERIVED。

Here's what I'm trying to do (this code doesn't work):

class Base
{
    virtual Base *clone() { return new Base(this); }
    virtual void ID() { printf("BASE");
};

class Derived : publc Base
{
    virtual Base *clone() { return new Derived(this); }
    virtual void ID() { printf("DERIVED"); }
}

.
.
Derived d;
Base *bp = &d;
Base *bp2 = bp->clone();

bp2->ID();

What I'd like is to see "DERIVED" printed out... what I get is "BASE". I'm a long-time C programmer, and fairly experienced with C++... but I'm not making any headway with this one... any help would be appreciated.

解决方案

Once all the compile errors are fixed, I ended up with this:

#include <cstdio>

class Base
{
  public:
    Base() {}
    Base(const Base&) {}
    virtual Base *clone() { return new Base(*this); }
    virtual void ID() { printf("BASE"); }
};

class Derived : public Base
{
  public:
    Derived() {}
    Derived(const Derived&) {}
    virtual Base *clone() { return new Derived(*this); }
    virtual void ID() { printf("DERIVED"); }
};


int main()
{
  Derived d;
  Base *bp = &d;
  Base *bp2 = bp->clone();

  bp2->ID();
}

Which gives you what you are looking for -- DERIVED.

这篇关于派生C ++类如何通过基指针来克隆本身?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆