派生的 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"); }
}
.
.
Derived d;
Base *bp = &d;
Base *bp2 = bp->clone();
bp2->ID();
我喜欢是看到“DERIVED”打印出来......我得到的是“BASE”。我是一名长期的 C 程序员,并且对 C++ 相当有经验...但我在这方面没有取得任何进展...任何帮助将不胜感激。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
一旦所有的编译错误都被修复,我最终得到了这个:
这给了你你正在寻找的东西——派生的。
Once all the compile errors are fixed, I ended up with this:
Which gives you what you are looking for -- DERIVED.
该代码充满了语法错误。也许最重要的是,Derived 并不继承自 Base。其次,除了语法错误(可能是简单的拼写错误)之外,Base 显然需要一个虚拟析构函数。克隆方法几乎要求您可以在基指针(Base*)上调用删除操作符。
That code is riddled with syntactical errors. Perhaps most significantly, Derived doesn't inherit from Base. Secondly, aside from the syntactical errors (probably simple typos), Base obviously needs a virtual destructor. The clone method pretty much demands that you can call operator delete on a base pointer (Base*).
使用
Base bp = &d;
您已经“切片”了
d
,因此对于编译器来说,bp
实际上只是Base
,这就是为什么当您调用bp->clone()
时,编译器会调用Base::clone();
和bp2- >ID()
打印BASE
。基础& bp = d;
会做你想做的事。With
Base bp = &d;
You've "sliced"
d
, so to the compiler,bp
really is only of typeBase
, which is why when you callbp->clone()
the compiler callsBase::clone();
andbp2->ID()
printsBASE
.Base& bp = d;
will do what you want.您正在切片
Base bp = &d; (这会从导出的指针构造一个新的基本 bp。)
尝试使用
Base* bp = &d;
代替。 (即创建一个指向 Derived 对象的 Base 类型的指针。)You're slicing the class in
Base bp = &d;
(this constructs a new base bp from the derived-ptr.)Try
Base* bp = &d;
instead. (i.e. create a pointer of Base type to the Derived object.)您的示例不正确,无法编译。具体来说这一行:
这也可能是您问题的根本原因(您可能正在切片您的对象),但如果没有看到工作代码,我无法确定。
您还遇到一个问题,即您的两个类不相关(您的意思是编写
class Derived : public Base
吗?)Your example is incorrect and will not compile. Specifically this line:
That may also be the root cause of your problem (you may be slicing your object), but I can't tell for certain without seeing working code.
You also have a problem where your two classes are not related (did you mean to write
class Derived : public Base
?)除了愚蠢的语法拼写错误和缺失的因素之外,代码看起来不错。
The code looks fine, other than the silly syntax typos and the missing ctors.