尝试将结构指针传递给类时出错

Error in trying to pass Struct pointer to class

本文关键字:出错 结构 指针      更新时间:2023-10-16

我正在开发一款游戏,我目前正在尝试制作一个播放器结构来存储玩家信息,例如姓名。我想创建一个类来划分代码段,以便在我的主.cpp中更干净的代码。

我有我的结构:

   //in main.cpp
 #include "player.h"
class MyClass player
    struct _Player {
        std::string name;
        int hp;
        int mana;
        int def;
        int mana_regen;
        int hp_regen;
    } player1;
void playerinfo2(_Player *playerx) {
    playerx->name = "test2";
}
int main() {
    player1.name = "test1";
    std::cout << player1.name << std::endl;
    playerinfo2(&player1);
    std::cout << player1.name;
    player.playerinfo(&player1);
}

此代码正在工作,并且正在将玩家 1 的名称从"test1"更改为"test2"。

//in player.h   
class MyClass {
struct _Player {
    std::string name;
    int hp;
    int mana;
    int def;
    int mana_regen;
    int hp_regen;
};
public:
void player_update();
void playerinfo(_Player *self);
private:
};

我不知道该结构是否需要同时存在于标题和.cpp文件中,但如果我不这样做,它会说"未知_Player"。

//in player.cpp
#include "player.h"
struct _Player {
    std::string name;
    int hp;
    int mana;
    int def;
    int mana_regen;
    int hp_regen;
};
void Player::player_update() {
    playery.mana = playery.mana + playery.mana_regen;
}
void Player::playerinfo(_Player *self) {
    self->name = "test3";
}

在控制台 g++ 主.cpp播放器中运行时.cpp -o 测试.exe我收到错误消息:

main.cpp: In function 'int main()':
main.cpp:29:29: error: no matching function for call to 'Player::playerinfo(_Player*)'
     test.playerinfo(&player1);
                             ^
In file included from main.cpp:4:0:
player.h:21:6: note: candidate: void Player::playerinfo(Player::_Player*)
 void playerinfo(_Player *self);
      ^~~~~~~~~~
player.h:21:6: note:   no known conversion for argument 1 from '_Player*' to 'Player::_Player*'

有什么方法可以将我的 player1 传递给类,就像我在 main .cpp 中使用我的函数一样?

不,您只需要在头文件(例如 player.h(中定义一次类,并在所有类文件中使用 #include player.h。如果您有播放器类的任何函数,则约定您可以在头文件中声明它们并.cpp文件中定义它们。您也可以在头文件中声明和定义它们并避免.cpp文件,但它可能会导致代码混乱。

我通过将我的类重命名为未使用的名称来解决这个问题,仅将结构放在 player.h 中,在 main 中声明 player1.cpp然后发送 player1,就像我将其发送到 playerinfo2 函数一样。

//in main.cpp
#include "player.h"
class MyClass test;

userPlayer player1;
void playerinfo2(userPlayer *self) {
    self->name = "test1";
}
int main() {
    playerinfo2(&player1);
    std::cout << player1.name;
    test.playerinfo(&player1);
    std::cout << player1.name;
}

//in player.h
#include <string>
#include <iostream>
struct userPlayer {
    std::string name;
    int hp;
    int mana;
    int def;
    int mana_regen;
    int hp_regen;
};
class MyClass {
public:
void player_update();
void playerinfo(userPlayer *self);
private:
};
//in player.cpp
#include "player.h"

void MyClass::playerinfo(userPlayer *self) {
    self->name = "test3";
}

这个更新的代码对我有用。