我有两个c ++类,比如说:
class A{
//Stuff from class B
};
class B{
//Stuff from class A
};
我决定从实现中分离接口,所以我有A.h和B.h头文件。 如何管理包含? A.h需要包括B.h,反之亦然,但这给了我编译器错误。我该怎么办?
编辑: 这些是标题。
Vertex.h
/*
* Vertex.h
*
* Created on: Jun 24, 2014
* Author: marco
*/
#ifndef VERTEX_H_
#define VERTEX_H_
#include <string>
#include <iostream>
#include <map>
#include "Edge.h"
namespace MarcoGraphs {
class Vertex {
private:
//Variables
std::string id;
int soglia;
double peso;
bool visited,convinto;
std::map<std::string, Edge*> archi;
//Disabled operations
Vertex(const Vertex& param);
Vertex& operator=(const Vertex&);
Vertex(Vertex&&);
Vertex& operator=(Vertex&&);
public:
Vertex(std::string id);
~Vertex();
std::map<std::string, Edge*>::iterator begin();
std::map<std::string, Edge*>::iterator end();
bool operator==(const Vertex& param) const;
bool operator<(const Vertex& param) const;
std::string getId() const;
int getDegree() const;
void setSoglia(int soglia);
int getSoglia() const;
void setVisited(bool value);
bool isVisited() const;
void setConvinto(bool value);
bool isConvinto() const;
void setPeso(double peso);
double getPeso() const;
bool addEdge(Edge& param);
bool removeEdge(Edge& param);
};
std::ostream& operator<<(std::ostream& out, const Vertex& a);
} /* namespace MarcoGraphs */
#endif /* VERTEX_H_ */
Edge.h
/*
* Edge.h
*
* Created on: 29/giu/2014
* Author: Marco
*/
#ifndef EDGE_H_
#define EDGE_H_
#include "Vertex.h"
namespace MarcoGraphs {
class Edge {
private:
//Variables
Vertex* side1;
Vertex* side2;
//Forbidden operations
Edge(const Edge& e);
Edge& operator=(const Edge& e);
Edge(Edge&& e);
Edge&& operator=(Edge& e);
public:
Edge(const Vertex& v1, const Vertex& v2);
Vertex& getSide1();
Vertex& getSide2();
Vertex& getOtherEnd(const Vertex& thisEnd);
~Edge();
};
std::ostream& operator<<(std::ostream& out, const Edge& a);
} /* namespace MarcoGraphs */
#endif /* EDGE_H_ */
错误如下:
In file included from ..\Vertex.h:13:0,
from ..\Graph.h:10,
from ..\Graph.cpp:8:
..\Edge.h:17:2: error: 'Vertex' does not name a type
Vertex* side1;
^
..\Edge.h:18:2: error: 'Vertex' does not name a type
Vertex* side2;
^
..\Edge.h:25:13: error: 'Vertex' does not name a type
Edge(const Vertex& v1, const Vertex& v2);
^
..\Edge.h:25:21: error: ISO C++ forbids declaration of 'v1' with no type [-fpermissive]
Edge(const Vertex& v1, const Vertex& v2);
^
..\Edge.h:25:31: error: 'Vertex' does not name a type
Edge(const Vertex& v1, const Vertex& v2);
^
..\Edge.h:25:39: error: ISO C++ forbids declaration of 'v2' with no type [-fpermissive]
Edge(const Vertex& v1, const Vertex& v2);
^
..\Edge.h:26:2: error: 'Vertex' does not name a type
Vertex& getSide1();
^
..\Edge.h:27:2: error: 'Vertex' does not name a type
Vertex& getSide2();
^
..\Edge.h:28:2: error: 'Vertex' does not name a type
Vertex& getOtherEnd(const Vertex& thisEnd);
答案 0 :(得分:0)
// header A;
class B;
class A {
B* b;
};
// header B
class A;
class B {
A* a;
};
你必须使用指针,否则编译器无法弄清楚A或B需要多少空间,因为为了计算A的大小,你必须计算B的大小,为此你需要计算大小A.又名递归