我现在遇到问题,我有两个类,并且试图从另一个类访问结构体中定义的变量。如果我尝试从其默认位置访问该特定变量,则返回的结果很好,但是如果我尝试从另一个类访问该变量,则返回的结果为0。我尝试调试,但是它什么也没做(无济于事)所以我不知道问题出在哪里。我在这里问这个问题是不得已而为之,因为我到处搜索了这个特定问题,但无法得出结论。

该结构是在CBasePlayer类之外定义的:

//Player table definition
typedef struct _PlayerInfo {
    char name[MAX_PLAYER_NAME];
    char playermodel[24];
    BYTE score;
    BYTE ping;
    UINT8 connected;
    UINT8 pactive;
    UINT8 pspawned;
    UINT8 pconnected;
    UINT8 pfakeclient;
    UINT8 pedicts;// Table - open with memOpen
    string pname;
    UINT8 puserid;
    string puserinfo;
    int pconnecttime;
    UINT8 plagcompensation;
    UINT8 pnext_messageinterval;
    int pnext_heartbeat;
    int plast_heartbeat;
    int pinternaluserid;
} PlayerInfo;


我把它放在CPP文件的顶部(它不在任何类中):

std::vector<_PlayerInfo> players;


我从名为CNetwork的类中调用的函数:

int CBasePlayer::GetBeat( int playerid, int type ) { //1 for next, 2 for last
    setPointerForPlayerID(playerid);
    std::vector<_PlayerInfo>::iterator it = players.begin();
    _PlayerInfo player;
    int i = 0;
    int value = 0;
    while(it != players.end()) { //This is where player.plast_heartbeat and player.pnext_heartbeat become 0
        player = *(it++);
        if(playerid == player.pinternaluserid) {
            value = (type == LAST_BEAT) ? player.plast_heartbeat : player.pnext_heartbeat;
        }
    }
    return value;
}


* player.plast_heartbeat *和* player.pnext_heartbeat *从不同的类访问时均为0,但它们的值恰好在其自己的类中(因此,即使从另一个类访问时它们显示为“ 0”,它们也确实会实际上有一个值)。

这就是我访问它们的方式:

void CNetwork::OnPreClientDisconnect( void ) { //Can't do int playerid here, once the heartbeat is gone all the info is lost on disconnect and it can't be parsed from the server
    CBasePlayer * pPlayer = new CBasePlayer;
    int lastbeat, nextbeat;
    for(int i=0; i<pPlayer->NumClients(); i++) {
        pPlayer->setPointerForPlayerID(i);
        nextbeat = pPlayer->GetBeat( i, NEXT_BEAT );
        lastbeat = pPlayer->GetBeat( i, LAST_BEAT );
        if(pPlayer->IsClientOnTable(i)) {
            if(pPlayer->LostBeat(lastbeat, nextbeat))
                OnClientDisconnect(i, REASON_DISCONNECT); //They lost the heartbeat, remove them from the table and disconnect them. If anything, they'll be readded to the table on the next queue.
        }
    }
    free(pPlayer);
}


我在类中也遇到过无数次此问题,因此我必须通过将其所有变量设为静态然后对其进行初始化来解决此问题。
预先感谢,非常感谢您的帮助,对于发布如此多的代码,我深表歉意。知道为什么值会像这样“重置”,这对我很有帮助,因为我已经有很长时间了。

更新,这是视频:

https://www.youtube.com/watch?v=PXKFjiStrKo&feature=youtu.be

以下是可编译的示例:[31/03/2014]

http://www.iw-rp.com/files/compilable_example.zip

最佳答案

据我了解,std :: vector 播放器是CBasePlayer的成员,因此此类的每个实例都有其自己的播放器矢量。每次创建此类的新实例时:CBasePlayer * pPlayer = new CBasePlayer;您创建了一个新的玩家载体。我不确定如何将向量作为此类的实例共享。如您所说,将向量定义为静态将解决您的问题。您可能想做的是改为让std :: vector 播放器成为CNetwork类的成员,以便您可以从OnPreClientDisconnect()之类的函数中访问它。

09-28 13:05