c – 非静态成员函数的非法调用

前端之家收集整理的这篇文章主要介绍了c – 非静态成员函数的非法调用前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在下面的这个功能有问题:
char* GetPlayerNameEx(int playerid)
{

    char Name[MAX_PLAYER_NAME],i = 0;

    GetPlayerName(playerid,Name,sizeof(Name));

    std::string pName (Name);

    while(i == 0 || i != pName.npos)
    {
        if(i != 0) i++;
        int Underscore = pName.find("_",i);
        Name[Underscore] = ' ';
    }
    return Name;
}

宣言:

char* GetPlayerNameEx(int playerid);

用法

sprintf(string,"%s",CPlayer::GetPlayerNameEx(playerid));

现在我的问题是

删除了个人信息.

如果这与我怀疑它有什么关系,那么这个函数包含在“Class”头(Declartion)中.

此外,我不知道为什么,但我不能让“代码”框正确适合.

解决方法

您不能将这些函数创建为静态(没有大量调整),因为您试图修改特定实例的数据.要解决您的问题:
class CPlayer
{
public:
    // public members

    // since you are operating on class member data,you cannot declare these as static
    // if you wanted to declare them as static,you would need some way of getting an actual instance of CPlayer
    char* GetPlayerNameEx(int playerId);
    char* GetPlayerName(int playerId,char* name,int size);
private:
    // note:  using a std::string would be better
    char m_Name[MAX_PLAYER_NAME];
};

// note:  returning a string would be better here
char* CPlayer::GetPlayerNameEx(int playerId)
{
    char* Name = new char[MAX_PLAYER_NAME];
    memset(Name,MAX_PLAYER_NAME,0);
    GetPlayerName(playerId,m_Name,sizeof(m_Name));
    std::string sName(m_Name);
    std::replace(sName.begin(),sName.end(),'_',' ');
    ::strncpy(sName.c_str(),MAX_PLAYER_NAME);
    return Name;
}
// in your usage
CPlayer player;
// ...
sprintf(string,player.GetPlayerNameEx(playerid));
原文链接:https://www.f2er.com/c/114826.html

猜你在找的C&C++相关文章