那将是那些 super 简单的问题之一,但我真的无法提醒自己为什么会这样。所以:我有一个简单的构造函数,我在其中初始化了一些变量,在这个例子中是 int,我还有一个方法可以帮助我打印出这个 int。但问题是在构造函数中我有正确的 int 值,但在外面我得到了一些随机的东西。为什么会发生这种情况以及如何预防?
这是 player.cpp:
#include "player.h"
#include <iostream>
player::player()
{
int position = 1;
}
void player::get_pos()
{
std::cout << "You position is: " << this->position << std::endl;
}
和player.h
#ifndef PLAYER_H
#define PLAYER_H
class player
{
int position;
public:
player();
void get_pos();
};
#endif // PLAYER_H
我也尝试过不使用 this->position
但它仍然不起作用。这对我来说似乎很准确,因为我想知道这个对象的位置。
最佳答案
你的构造函数:
player::player()
{
int position = 1;
}
正在声明一个名为 position
的局部变量并设置它,而不是按预期设置类成员。
尝试:
player::player()
{
position = 1;
}
关于c++ - 类成员在构造函数中和构造函数外的不同值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39765205/