错误 22 错误 C2228:'.size'左侧必须具有类/结构/联合
Error 22 error C2228: left of '.size' must have class/struct/union
我知道有很多重复的答案,但似乎没有一个答案有帮助。
class Vertex
{
public:
string name; // Vertex name
vector<Vertex *> adj; // Adjacent vertices
int dist; // Cost
Vertex *path; // Previous vertex on shortest path
bool visited;
Vertex( const string & nm ) : name( nm )
{ reset( ); }
void reset( )
{ dist = INFINITY; path = NULL; }
};
void Graph::explore(Vertex *v)
{
//error for v.visited
//error for anything where 'v' is referenced.
v.visited = true;
int total;
for(int i = 0; i < v.adj.size(); i++)
{
cout << v.adj.name << " to ";
if (!v.visited)
{
explore(v.adj[i]);
}
}
}
阅读其他帖子后,我无法确定错误的原因。(我是 c++ 的新手)。其他人能看到什么吗?该错误也存在于其他方法中。
v
是一个指针,所以你需要使用指针成员访问运算符(->
)而不是对象成员访问运算符(.
)。
void Graph::explore(Vertex *v)
{
v->visited = true;
int total;
for(int i = 0; i < v->adj.size(); i++)
{
cout << v->name << " to "; // this should be v->name,
// not v->adj.name
if (!v->visited)
{
explore(v->adj[i]);
}
}
}
void Graph::explore(Vertex *v)
将 v 定义为指向顶点的指针。 您可以使用 v->member 引用它的成员。我建议将定义更改为:
void Graph::explore(Vertex &v)
它将 v 定义为顶点(使用引用),它只是一个优化,以便在调用函数时不会堆叠整个数据结构。 然后你可以以 v.member 的身份访问 v 的成员
另一种解决方案(不推荐,使用参考更好)是
void Graph::explore(Vertex *v)
{
//error for v.visited
//error for anything where 'v' is referenced.
v->visited = true;
int total;
for(int i = 0; i < v->adj.size(); i++)
{
cout << v->adj.name << " to ";
if (!v->visited)
{
explore(& (v->adj[i]) );
}
}
}
这会将 v 定义为指向顶点的指针,但它会更改成员访问和递归调用以反映这一点。
相关文章:
- 错误 C2228 左侧'.setDay'必须具有类/结构/联合
- for 循环说 - 错误 成员引用基类型"int [13]"不是结构或联合
- C 匿名联合重新陈述错误
- 错误:成员引用基类型"uint32_t"(也称为"无符号 INT")不是结构或联合
- C++错误 C2227:'->looseHealth'左侧必须指向类/结构/联合/泛型类型
- 联合 int 位到浮点位有时解释错误
- 编译错误向量排序和联合
- C++ 与函数联合,Arduino编译器错误"cannot be overloaded"
- 在构造函数的成员初始值设定项列表中使用带有指示符的初始值设定项列表以初始化匿名联合类型时出现编译错误
- 编译时错误:删除了联合默认构造函数
- 错误c++visual studio c2227左侧'->;Init';必须指向类/结构/联合/泛型类型
- 联合中的友元函数中出现错误"... does not name a type" - 为什么?如何解决?
- C++ 错误 - <unnamed-tag>不允许匿名联合的成员使用 cass 内初始值设定项
- 错误:在不是结构或联合的某些内容中要求成员“ prev_”
- 我的测试用例错误类/结构/联合
- C++ 异常情况下的错误 C2228(".val"的左侧必须具有类/结构/联合)
- 错误 C2228:".x"的左侧必须具有类/结构/联合
- 错误:C2228:左侧必须具有类/结构/联合
- 错误 C2228:".printStats"的左侧必须具有类/结构/联合
- 错误 C228:"必须多次具有类/结构/联合"的左侧