开发者

Array of an Object

I need to do something that I think is called an Object Array. For example: A player accesses the server, this server will allocate this player as an object of such a group, so will have many objects of the same class.

Is there a way to make using one line for each player, but would have to be a source editing and compilation in real time and without stopping the server, which is impossible, but to demonstrate:

Player p0000001 ("Nickname", 150);
Player p0000002 ("OtherNickname", 17);
Player pNNNNNNN ("Nick", 00);

I wanted something like:

Player players[0].nickname = "Nickname";
Player players[0].level = 150;
Player players[1].nickname = "OtherNickname";
Player players[1].level = 17;

It's possible this? I just need a demo for me to adapt. Thanks,开发者_运维知识库 Bruno Alano.


The best thing would be to use one of the STL containers such as std::vector:

#include <vector>

std::vector<Player> players;
players.push_back(Player("Nickname", 150));

A full reference to std::vector can be found on cplusplus.com.


If I understood you right, you want to handle an unknown amount of players dynamically(meaning you cant hardcode it at compile time). That usually implies dynamic memory allocation with new/delete. As you don't know how many players there will be you should use a data structure of dynamic size, like std::vector or std::list.

If you use an std::vector/list try to handle pointers and not objects themselves because that triggers copy-constructors, destructors and therefore a whole lot of unnecessary operations for just holding these values.


I'm not sure, but I think you need a C++ program monitoring an input file. Is that true? If it is, you just need the program to read each new line (i.e. while !eof). The client will open the file in append mode and will add the lines as new users join the server.

You can find some code here:

http://www.dreamincode.net/forums/topic/222664-how-to-read-continuously-refreshed-file-in-c/

Hope this helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜