从 Java 对象类到 C++
我对 C++ 比较陌生,我的背景是 Java。我必须将一些代码从 Java 移植到 C++,并且出现了一些与 Java 对象类相关的疑问。所以,如果我想移植这个:
void setInputParameter(String name, Object object) { ..... }
我相信我应该使用 void* 类型或模板,对吗?我不知道完成它的“标准”程序是什么。
谢谢
I'm relative new to C++ and my background is in Java. I have to port some code from Java to C++ and some doubts came up relative to the Object Java's class. So, if I want to port this:
void setInputParameter(String name, Object object) { ..... }
I believe I should use void* type or templates right? I don't know what's the "standard" procedure to accomplish it.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这取决于您想用
对象做什么
。如果您使用模板,那么您在
object
上调用的任何方法都将在编译时绑定到object
的类型。这是类型安全的,并且更可取,因为对该对象的任何无效使用都将被标记为编译器错误。您还可以传递一个
void *
并将其转换为所需的类型,假设您有某种方式知道它应该是什么。这更危险并且更容易出现代码中的错误。您可以通过使用dynamic_cast
启用运行时类型检查来使其更安全。It depends what you want to do with
object
.If you use a template, then any methods you call on
object
will be bound at compile time toobject
s type. This is type safe, and preferable, as any invalid use of the object will be flagged as compiler errors.You could also pass a
void *
and cast it to the desired type, assuming you have some way of knowing what it should be. This is more dangerous and more susceptible to bugs in your code. You can make it a little safer by usingdynamic_cast<>
to enable run-time type checking.如果您想接受指向任意对象的指针,那么您会希望类型为
void *
。但是,这将是函数的结尾,除了存储它的值或将其转换为指向某个已知对象的指针之外,您不能对 void * 执行任何操作。如果您无论如何都要强制转换它,那么您可能知道该对象是什么,因此您不需要void *
。C++ 只是不具备 Java 那样的自省能力。换句话说,没有一种方便的方式来表达诸如
myObject.getClass().getName()
之类的内容。我所知道的最接近的是运行时类型信息(RTTI),您可以在此处查看它的实际情况。另一种选择是创建您自己的根类,并编写您自己的内省方法(许多 C++ 框架都这样做)。
If you want to accept a pointer to an arbitrary object, then you would want the type to be
void *
. However, that would be the end of the function, you can't do anything with avoid *
except store it's value or cast it to a pointer to some known object. If you're going to cast it anyway, then you probably know what the object is, so you don't need thevoid *
.C++ just doesn't have the same kinds of introspection abilities that Java has. In other words, there's not a convenient way to say something like
myObject.getClass().getName()
. The closest thing that I'm aware of is runtime type information (RTTI), which you can see in action here.The other alternative is to create your own root class, and write your own introspection methods (a lot of C++ frameworks do this).