尝试将结构指针传递给类时出错
Error in trying to pass Struct pointer to class
我正在开发一款游戏,我目前正在尝试制作一个播放器结构来存储玩家信息,例如姓名。我想创建一个类来划分代码段,以便在我的主.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";
}
这个更新的代码对我有用。
相关文章:
- 为什么我在初始化带大括号的结构时出错?
- 尝试将指针与结构一起使用时出错
- PCL 出错:体系结构x86_64 @pcl的未定义符号
- 尝试初始化结构内的联合时出错
- 当使用 std::CIN 输入结构时,它会出错
- 在 boost::heap::p riority_queue 中推送结构对象时出错
- 确定输入"conscalc: calc"的类型时出错。不能联合编码器。具有不同字段集的结构类型
- 尝试将数据添加到结构内部的矢量时出错
- 使用提升库在队列和堆栈数据结构上保存和加载数据时出错
- 尝试将结构指针传递给类时出错
- 在旧的 c++ (<c++11) 中,初始化结构会出错
- 类中私有结构的构造函数出错
- 读取结构数组时出错
- 将模板参数传递到内部结构时出错
- 创建局部结构的 std::向量时出错
- 在 C++ 中访问泛型结构的成员会出错
- 使用映射<字符串,结构>类型的映射编译头文件时出错
- 使用单元测试 (cppunit) 中另一个文件中定义的结构时出错
- 初始化作为结构成员的函数指针时出错
- 使用嵌套结构将结构作为引用传递时出错