此以下线程程序内的实例:C++不能修改类
void* Nibbler::moveRoutine(void* attr)
{
[...]
Nibbler* game = static_cast<Nibbler*>(attr);
while (game->_continue == true)
{
std::cout << game->_snake->_body.front()->getX() << std::endl; // display 0
std::cout << game->getDirection() << std::endl; // display 0
game->moveSnake();
std::cout << game->_snake->_body.front()->getX() << std::endl; // display 0
std::cout << game->getDirection() << std::endl; // display 42
}
}
[...]
}
我打电话成员函数moveSnake(),这是应该修改形成我的蛇的身体细胞的位置。
void Nibbler::moveSnake()
{
[...]
std::cout << this->_snake->_body.front()->getX() << std::endl; // display 0
this->_snake->_body.front()->setX(3);
this->_direction = 42;
std::cout << this->_snake->_body.front()->getX() << std::endl; // display 3
[...]
}
虽然我的两个坐标我moveSnake内有效地修改()函数,它们不再当我回到我的常规,在那里他们保持初始值。我不明白为什么会发生这种情况,因为如果我尝试在我的moveSnake()函数内修改我的类的任何其他值,则实例会被修改,并且会将此值保留在例程中。
了冲切类:
class Nibbler
{
public :
[...]
void moveSnake();
static void* moveRoutine(void*);
private :
[...]
int _direction
Snake* _snake;
IGraphLib* _lib;
pthread_t _moveThread;
...
};
蛇:
class Snake
{
public :
[...]
std::vector<Cell*> _body;
};
最后的细胞:
class Cell
{
public :
void setX(const int&);
void setY(const int&);
int getX() const;
int getY() const;
Cell(const int&, const int&);
~Cell();
private :
int _x;
int _y;
};
的cell.cpp代码:
void Cell::setX(const int& x)
{
this->_x = x;
}
void Cell::setY(const int& y)
{
this->_y = y;
}
int Cell::getX() const
{
return this->_x;
}
int Cell::getY() const
{
return this->_y;
}
Cell::Cell(const int& x, const int& y)
{
this->_x = x;
this->_y = y;
}
Cell::~Cell()
{}
在我看来,你是在一个多线程环境(或者我没有看到'moveRoutine'使用静态方法的观点)。也许另一个线程在同一时间重新初始化数据。并且要在C++中创建一个线程,如果需要,最好使用'std :: thread'并最终使用'std :: bind',这将保留类结构并防止使用'void *' – Geoffroy
我在这里使用的唯一线程是调用moveRoutine的那个。此外,如果我在moveSnake()中设置了任何其他属性,它将起作用,所以我猜测问题来自于我以这种方式在我的向量中设置Cell的事实,但我看不出为什么。 – Kernael
你可以显示set()和get()的代码吗?我没有看到你的代码不能工作的原因。 @Geoffrey:另一个线程怎么会在那里干扰?除非在Snake中有一个reset()方法或类似的东西。显示的用于设置和获取的测试代码显然是在单个线程中,所以不应该存在缺失写入问题。 –