错误 22 错误 C2228:'.size'左侧必须具有类/结构/联合

Error 22 error C2228: left of '.size' must have class/struct/union

本文关键字:错误 联合 结构 C2228 size      更新时间:2023-10-16

我知道有很多重复的答案,但似乎没有一个答案有帮助。

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 定义为指向顶点的指针,但它会更改成员访问和递归调用以反映这一点。