C++ 如何实现模板类的正向声明
我正试图通过使用嵌套类C++ 如何实现模板类的正向声明,c++,templates,inner-classes,forward-declaration,C++,Templates,Inner Classes,Forward Declaration,我正试图通过使用嵌套类顶点和边创建一个图形类。我想让我的Vertex类接受泛型参数。我已经向前声明了我的顶点类,以便我可以在边类中使用它 当我使用模板时,我会遇到一些不确定如何解决的错误 这是我试过的。错误会在每行旁边注释掉 class Graph { private: template <class T> class Vertex; // Forward Declaration template <class T>
顶点
和边
创建一个图形
类。我想让我的Vertex
类接受泛型参数。我已经向前声明了我的顶点
类,以便我可以在边
类中使用它
当我使用模板时,我会遇到一些不确定如何解决的错误
这是我试过的。错误会在每行旁边注释掉
class Graph
{
private:
template <class T>
class Vertex; // Forward Declaration
template <class T>
vector<Vertex<T> > vertices; // Err: member 'vertices' declared as a template
class Edge
{
public:
template <class T>
Vertex<T>& _orig; // Err: member '_orig' declared as a template
template <class T>
Vertex<T>& _dest; // Err: member '_dest' declared as a template
template <class T>
Edge(Vertex<T>& orig, Vertex<T>& dest) : _orig(orig), // Err: member initializer '_orig' does not name a non-static data member or base class
_dest(dest) { }
template <class T>
Vertex<T>& getOrig() { return _orig; } // Err: use of undeclared identifier '_orig'
template <class T>
Vertex<T>& getDest() { return _dest; } // Err: use of undeclared identifier '_dest'
};
template <typename T>
class Vertex
{
public:
T _data;
vector<Edge> _edges;
Vertex(T data) : _data(data) { }
void addEdgeToVertex(Edge& edge)
{
_edges.push_back(edge);
}
};
public:
template <typename T>
void addEdge(Vertex<T>& orig, Vertex<T>& dest)
{
Edge edge(orig, dest);
orig.addEdgeToVertex(edge);
dest.addEdgeToVertex(edge);
}
};
类图
{
私人:
模板
类Vertex;//前向声明
模板
向量顶点;//错误:成员“顶点”声明为模板
阶级边缘
{
公众:
模板
Vertex&\u orig;//错误:成员“\u orig”声明为模板
模板
Vertex&\u dest;//错误:成员“\u dest”声明为模板
模板
Edge(顶点和原点、顶点和目标):\u原点(原点),//错误:成员初始值设定项“\u原点”未命名非静态数据成员或基类
_目的地(目的地){}
模板
Vertex&getOrig(){return}//Err:使用未声明的标识符'\u orig'
模板
Vertex&getDest(){return _dest;}//错误:使用了未声明的标识符“_dest”
};
模板
类顶点
{
公众:
T_数据;
向量_边;
顶点(T数据):_数据(数据){
无效添加顶点(边和边)
{
_边缘。推回(边缘);
}
};
公众:
模板
无效添加(顶点和原点、顶点和目标)
{
边缘(起点、终点);
原始添加顶点(边);
目标添加顶点(边);
}
};
你能帮我指出我做错了什么吗?如何修复此代码?转发声明看起来不错。问题是不能声明“模板成员变量”,如何为它们指定模板参数 您应该改为创建类模板
template <class E>
class Graph
{
private:
template <class T>
class Vertex; // Forward Declaration
vector<Vertex<E> > vertices;
...
};
模板
类图
{
私人:
模板
类Vertex;//前向声明
向量顶点;
...
};
类Edge
也是如此
简化问题:查看如何声明不需要转发声明的模板数据成员。不能使用非静态的模板变量…谢谢。我找到了解决办法。但我不太明白。你能解释一下模板图是什么意思吗?i、 e.模板类顶点;向量顶点;用外行的话来说。对不起,这让我很困惑。如果我的数据是字符串类型,那么“E”和“T”都是字符串对吗?@SyncMaster如果使用
Graph
likeGraph g
,则模板参数E
将为std::string
,成员顶点
将为vector
。然后在顶点
中,\u数据
将是std::string
,\u边
将是向量
。