将基本类的对象扩展到复杂类的对象
我怎样才能做到这一点?我想到了复杂类中的一种方法,它将基本对象的每个变量复制到复杂对象,但这似乎有点不方便。
class Basic
{
//basic stuff
}
class Complex : public Basic
{
//more stuff
}
Basic * basicObject = new Basic();
//now "extending" basicObject and "cast" it to Complex type
//which means copy everything in basicObject to an complexObject
或者类似的东西:
Complex * complexObject = new Complex();
complexObject.getEverythingFrom(basicObject);
似乎太不方便了,因为每次我更改Basic类时,我也必须更改这个“复制”方法。
how can I do that? I thought of an method in the complex class which copies every variable of the basic object to the complex object, but that seems a little bit to inconvenient.
class Basic
{
//basic stuff
}
class Complex : public Basic
{
//more stuff
}
Basic * basicObject = new Basic();
//now "extending" basicObject and "cast" it to Complex type
//which means copy everything in basicObject to an complexObject
or something like:
Complex * complexObject = new Complex();
complexObject.getEverythingFrom(basicObject);
seems to be too inconvenient, because everytime I change the Basic class, I have to change this "copy" method too.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
定义要在受保护部分中的类之间共享的值,如下所示:
Define the values you want to share between the classes in protected section like so:
在 C++ 中,对象不能更改其类型。
因此,要么重写程序以立即创建
Complex
对象,要么创建一个复制构造函数,以便可以执行以下操作:new Complex(*basicObject);
旁注:从像extend这样的词和new的用法来看,你似乎来自java世界。不要错误地认为在 Java 中做事的方式也是在 C++ 中做事的方式。
In C++, objects can not change their type.
So either you rewrite your program to right away create
Complex
objects, or you create a copy ctor so that you can do:new Complex(*basicObject);
side note: from words like extend and the usage of new it seems you come from a java world. Don't make the mistake of thinking that how you do things in java is also how you do it in C++.