[英]C++ Pointer to an array of enum
I've got a problem with trying to point to a vector and then setting the value of an element when trying to de-reference it.我在尝试指向一个向量然后在尝试取消引用它时设置元素的值时遇到了问题。
std::vector < Maze::TILE_CONTENT> * theGrid;
if (go->team == GameObject::GT_BLUE)
*theGrid = m_myGridBlue;
else
*theGrid = m_myGridRed;
if (go->curr.y < m_noGrid - 1)
{
theGrid[next.y * m_noGrid + next.x] = Maze::TILE_EMPTY; //no operate '=' matches these operands
}
There are two problems here.这里有两个问题。 The first is in the assignment to
*theGrid
.第一个是对
*theGrid
的赋值。 This code will copy the source vector to whatever theGrid
points to.此代码将源向量复制到
theGrid
指向的任何位置。 Since that pointer is uninitialized, you have Undefined Behavior, a crash if you're lucky.由于该指针未初始化,因此您有未定义的行为,如果幸运的话会崩溃。 I think what you're trying to do is
我想你想做的是
theGrid = &m_myGridBlue;
The second problem, which gives your compilier error, is how you access the pointed-to vector.导致编译器错误的第二个问题是如何访问指向的向量。 Since
theGrid
is a pointer to a vector, you need to dereference that pointer first:由于
theGrid
是指向向量的指针,因此您需要先取消引用该指针:
(*theGrid)[next.y * m_noGrid + next.x] = ...;
As an alternative to the pointer, you can use a reference作为指针的替代,您可以使用引用
std::vector<Maze::TILE_CONTENT> &theGrid = go->team == GameObject::GT_BLUE ? m_myGridBlue : m_myGridRed;
then you can access the contents of theGrid
as you already are.然后您就可以像
theGrid
一样访问theGrid
的内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.