问题
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
回答1:
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 to object
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 using dynamic_cast<>
to enable run-time type checking.
回答2:
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 a void *
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 the void *
.
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).
来源:https://stackoverflow.com/questions/2648756/from-java-object-class-to-c