且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使模板化成员函数实例化给定类类型的对象

更新时间:2021-07-19 00:55:10

我修复了你的代码。将我所做的与原始代码进行比较。


在课堂定义之外调用它们时,不要忘记公开您的成员函数。



I fixed your code. Compare what I did to the original code.


Don''t forget to make your member functions public when calling them from outside the class definition.




展开 | 选择 | Wrap | 行号


不完全,但我很感激努力: - )


我认为你错过了内部存储的部分。问题是新对象不应该被发送出去,而是存储在里面。


我忘了提到的一件事:createObject函数的返回是新对象的id(或game-id)(所以返回0里面很好)。


主要区别在于模板类在代码中用作函数的返回类型,但不在我的代码中。
Not exactly, but I appreciate the effort :-)

I think you missed the part with "stores it internally". The thing is that the new object should not be sent out, but stored inside.

A thing I forgot to mention: the return of the createObject function is the id (or game-id) of the new object (so returning 0 inside is fine).

The main difference is that the template class is used as the return type of the function in you''re code, but not in my code.


createObject成员函数希望将创建的对象作为私有成员变量存储在其类中。这意味着类型为T的成员变量。这意味着模板类。


一种方法是在创建的对象上使用多态,这样类只需要存储一个基础类指针。


如果这不起作用,你可以设计一个包并将包放在类对象中,并使用包处理程序将创建的对象移入和移出。 />

你可能会看看微软和VARIANT。需要大量的类型转换,但易于使用。
The createObject member function would want to store the created object as a private member variable inside its class. That would mean a member variable of type T. That would mean a template class.

One way around that is to use polymorphism on the created objects so the class only needs to store a base class pointer.

If this doesn''t work you can design a bag and keep the bag in the class object and use a bag handler to move created objects in and out.

You might look at Microsoft and the VARIANT. Lots of typecasting required but easy to use.