【问题标题】:error C2027: use of undefined type 'edge'错误 C2027:使用未定义类型“边缘”
【发布时间】:2014-05-14 01:50:57
【问题描述】:

我在尝试编译时出现此错误。我寻求帮助,但所有答案都集中在包括分隔文件上。但这只是一个 .cpp 文件,所以没有帮助。我提到了“阶级优势”;在代码的开头。我已经包含了 iostream、string、map 和 set。

代码如下:

...

using namespace std;

class edge;

class vertex{
public:
    string name;
    set<edge*> edges;
    int distance;

    vertex(string name){
        this->name = name;
    }

    void print_neighbours(){
        cout << "vertex:" << name << "    neighbours: ";
        for(set<edge*>::iterator it = edges.begin(); it != edges.end(); it++){
            cout << (*it)->getVertex(this->name)->name << " "; //compile error here
        }
        cout << endl;
    }   
};

class edge{
public:
    vertex* from;
    vertex* to; 
    int length;

    edge(vertex* ver1, vertex* ver2, int length=1){
        this->from = ver1;
        this->to = ver2;
        this->length = length;
    }

    vertex* getVertex(string v1){
        if(v1 == this->from->name){
            return this->to;
        }
        else if(v1 == this->to->name){
            return this->from;
        }
    }

};

...

抱歉,这是我的第一天。

【问题讨论】:

  • 在定义 edge 类型之前,您在 vertex 函数的定义中使用了 edge 类型。在这种情况下,声明是不够的。如果您将edge 定义移到vertex 之前,则您的情况应该有效,并改为转发声明vertex
  • 将类声明放在头文件中,将成员函数的实现放在Cpp文件中。
  • 谢谢,我不知道这个方法

标签: c++ class types undefined


【解决方案1】:

您在此处调用edge 方法:

(*it)->getVertex(this->name)->name

所以你需要完整的edge 类定义。前向声明是不够的。

您可以通过将需要完整 vertex 定义的 edge 代码从 edge 定义移到实现文件中来解决此问题,反之亦然。

【讨论】:

  • 感谢您的评论。但正如你所看到的,另一方面,我在类边缘中使用顶点。所以它会产生相同的错误,但类型为“顶点”。
  • @user3631453 是的,你必须解决这个问题。对此有很多问题。基本上,将需要完整类定义的代码移动到实现文件中。
  • 我从来没有这样做过,这就是我不知道的原因。谢谢,会努力解决的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-04
  • 1970-01-01
相关资源
最近更新 更多