C++ 对象参数混淆
Posted
技术标签:
【中文标题】C++ 对象参数混淆【英文标题】:C++ object parameters confusion 【发布时间】:2020-05-09 19:20:55 【问题描述】:我在传递一个对象作为我的一个函数的参数时遇到问题(我认为)。 在我的一个名为 Engine.cpp 的类中,我从另一个名为 knight.cpp 的类中调用了一个函数。以下是两者的代码。
Engine.cpp
void Engine::player_controling(N5110 &lcd,Gamepad &pad)
knight.draw(lcd); //draws the knight in the starting position
Knight.cpp
void Knight::init() //starting postion for the knight
x_knight=42; //X-cordinate for the knight
y_knight=33; //Y-cordinate for the knight
void Knight::draw(N5110 &lcd) //draws the knight in the start pos
const int man[17][13] = //the array for the knight, 1=pixel turn on.
0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,1,0,1,0,1,0,0,0,0,0,0,
0,0,0,1,1,1,0,0,0,0,0,0,0,
0,0,0,1,1,1,0,0,0,0,0,0,0,
0,0,0,0,1,0,0,0,0,0,0,0,0,
0,1,1,1,1,1,1,1,0,0,0,0,0,
0,1,0,1,1,1,0,1,0,0,0,0,0,
0,1,0,1,1,1,0,1,0,0,0,0,0,
0,1,0,1,1,1,0,1,0,0,0,0,0,
0,1,0,1,1,1,0,1,0,1,0,0,0,
0,0,0,1,0,1,0,0,1,0,0,0,0,
0,0,0,1,0,1,0,1,0,1,0,0,0,
0,0,0,1,0,1,0,0,0,0,1,0,0,
0,0,0,1,0,1,0,0,0,0,0,1,0,
0,0,0,1,0,1,0,0,0,0,0,0,0,
0,0,0,1,0,1,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,
;
//draws the knight
lcd.drawSprite(x_knight,y_knight,17,13,(int *)man);
在main.cpp中,如果我直接调用
knight.draw(lcd);
然后它把骑士画在正确的位置,因为它把 x_knight 作为 42 和 y_knight 作为 33 从
knight.init()
但是在 main.cpp 中调用它
Engine.player_controling(lcd & pad);
表示它设置
x_knight=0
y_knight=0
这是默认值。 我如何获得 Engine.player_controlling(lcd &pad); 将 knight.init 识别为正确的值?
【问题讨论】:
代码看起来不完整 - 你在哪里调用knight.init()
? knight
对象是如何在 Engine
类中构造的(如果它是类成员)?基本上你需要确保在player_controling()
的函数调用之前为Knight
类调用Init()
。
【参考方案1】:
很可能Init()
函数在Engine::player_controling()
被调用之前没有被调用。
一种可能的解决方案可能是 - 您需要确保在 Engine::player_controling()
的函数调用之前调用 Knight::Init()
【讨论】:
【参考方案2】:根据这些代码 sn-ps 和行为,我猜你有多个 Knight 实例。
很可能,Engine 拥有的实例不是您调用 init 的那个实例。
应该是这样的:
class Engine
public:
// You have to initialize Knight inside your Engine.
Engine()
knight_.Init(); // This is (I guess) the missing part.
// Alternatively, you may want to pass an already initialized knight here.
Engine(const Knight& knight) : knight_(knight)
// ...
void PlayerControlling(N5110 &lcd,Gamepad &pad)
knight_.Draw();
private:
Knight knight_;
;
【讨论】:
以上是关于C++ 对象参数混淆的主要内容,如果未能解决你的问题,请参考以下文章