gpt4 book ai didi

c++ - 派生的 C++ 类如何通过基指针克隆自身?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:06:12 25 4
gpt4 key购买 nike

这是我正在尝试做的(这段代码不起作用):

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();

喜欢的是看到打印出“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();
}

它为您提供了您正在寻找的东西 - 派生。

关于c++ - 派生的 C++ 类如何通过基指针克隆自身?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3136646/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com