我在MyFile.h和MyFile.cc中实现我的Vertex类时收到以下错误
// MyFile.h
#ifndef FILE
#define FILE
#include <set>
class Vertex{
public:
int i, j;
set<Vertex*> adj; //references to adjacent vertices (max of 4)
Vertex();
~Vertex();
//end constructors
void setPos(int row, int col);
/** must overload for set<Vertex> to function */
const bool operator < (const Vertex &o) const;
};//END class Vertex
#endif
// MyFile.cc
#include "MyFile.h"
#include <set>
using namespace std;
Vertex::Vertex():i(-1), j(-1), adj(0,5)/*may store [0,4] elements*/{}
Vertex::~Vertex(){
adj.clear();
}
//end constructors
void Vertex::setPos(int row, int col){
i = row;
j = col;
}//end setPos()
/** must overload for set<Vertex> to function */
const bool Vertex::operator < (const Vertex &o) const{
if(i < o.i)
return true;
if(i > o.i)
return false;
return j < o.j;
}
/** connect v1 and v2 such that they are adjacent */
void addEdge(Vertex* v1, Vertex* v2){
v1->adj.insert(v2);
v2->adj.insert(v1);
}//end addEdge
我已经尝试了几种方法来实现该类,但我一直收到这个错误:
In file included from MyFile.cc:5:0:
MyFile.h:15:2: error: 'set' does not name a type
set<Vertex*> adj; //references to adjacent vertices (max of 4)
^
MyFile.cc: In constructor 'Vertex::Vertex()':
MyFile.cc:15:32: error: class 'Vertex' does not have any field named 'ad
j'
Vertex::Vertex():i(-1), j(-1), adj(0,5)/*may store [0,4] elements*/{}
^
MyFile.cc: In destructor 'Vertex::~Vertex()':
MyFile.cc:18:2: error: 'adj' was not declared in this scope
adj.clear();
^
MyFile.cc: In function 'void addEdge(Vertex*, Vertex*)':
MyFile.cc:39:6: error: 'class Vertex' has no member named 'adj'
v1->adj.insert(v2);
^
MyFile.cc:40:6: error: 'class Vertex' has no member named 'adj'
v2->adj.insert(v1);
^
make: *** [MyFile.o] Error 1
也许有些东西我不见了,因为我还在学习如何有效地使用头文件。有人能给我任何建议吗?
答案 0 :(得分:2)
您声明了一个字段
set<Vertex*> adj;
但你用
构建它adj(0,5);
您不能指望将5
转换为指向Vertex
我建议使用一些smart pointers,也许是shared_ptr
std::set<std::shared_ptr<Vertex>> adj;
假设C++11代码。
请详细了解C++ programming。另请阅读documentation of std::set
(注意"range constructor"想要迭代器到一些已经存在的集合中)
我会将adj
构造为空集并稍后填充(至少在Vertex
的构造函数内部
答案 1 :(得分:0)
以下错误消息提供了一个很好的线索:
In file included from MyFile.cc:5:0:
MyFile.h:15:2: error: 'set' does not name a type
set<Vertex*> adj; //references to adjacent vertices (max of 4)
您需要使用:
std::set<Vertex*> adj;
但是,以下代码行中的注释没有意义:
Vertex::Vertex():i(-1), j(-1), adj(0,5)/*may store [0,4] elements*/{}
std::set
没有一个能够完成您希望的构造函数。