使用结构体作为参数:错误:结构体未定义
Using structs as arguments: Error: Struct not defined
我正在创建一个类,其中我定义了一个名为"Room"的结构体,我在头文件中声明为私有。我有几个公共函数需要"Room"作为参数。当我编译(在g++中)时,我得到一个错误说:
Graph.h:42:17: error: "Room" has not been declared
但是这里有声明(现在是整个头文件):
#ifndef GRAPH_H
#define GRAPH_H
#include <iostream>
#include <string>
using namespace std;
class Graph {
public:
// destructor
~Graph();
// copy constructor
Graph(const Graph &v);
// assignment operator
Graph & operator = (const Graph &v);
//Create an empty graph with a potential
//size of num rooms.
Graph( int num );
//Input the form:
//int -- numRooms times
//(myNumber north east south west) -- numRooms times.
void input(istream & s);
//outputs the graph as a visual layout
void output(ostream & s) const;
//Recursively searches for an exit path.
void findPath( Room start );
//Moves room N E S or W
void move( Room &*room , String direction );
//inputs the starting location.
void inputStart( int start );
//Searches the easyDelete array for the room with the
//number "roomNumber" and returns a pointer to it.
const Room * findRoom( int roomNumber );
private:
struct Room
{
bool visted;
int myNumber;
Room *North;
Room *East;
Room *South;
Room *West;
};
int numRooms;
int _index;
int _start;
Room ** easyDelete;
string * escapePath;
Room * theWALL;
Room * safety;
};
#endif
不允许使用头文件中定义的结构体作为参数吗?如果是这样,解决方法是什么?
谢谢。
没有private:
标头也可以很好地编译。你怎么会有这个?结构是在类内部声明的吗?
编辑
在声明Room
之前,您已经使用了它:
const Room * findRoom( int roomNumber );
同样,你不能通过你声明的公共方法返回Room
对象,因为外部代码不会知道它的任何信息。
你需要在使用它之前预先声明它:
class Graph {
public:
struct Room;
const Room * findRoom( int roomNumber );
struct Room
{
bool visted;
int myNumber;
Graph::Room *North;
Graph::Room *East;
Graph::Room *South;
Graph::Room *West;
};
Room room;
};
int main (){
Graph x;
return 0;
}
或者您可以将第二个private
向上移动,置于public
部分之上。
如果您使用嵌套结构体作为包含类的方法的参数,那么您必须使用全限定名称,例如void outerclass::mymethod(outerclass::room);
。您可能还需要将其设置为public
- 房间不能是私有的,因为你在公共成员函数中使用它。
-
或者像这样向前声明:
struct Room; // destructor ~Graph();
-
或者在使用它之前在类的顶部声明并实现它
-
void move( Room &*room , String direction ); //this is not valid C++
您必须在使用任何类型之前声明它。前向声明就足够了,因为您在同一作用域中定义了Graph::Room
。然而,既然你必须定义它,我建议在第一次使用它之前把它移到某个位置。
在Graph
中设置Room
为私有是完全合法的(但如果您的公共接口与之混淆,那么它是否合理是值得怀疑的)。
附带说明:指向引用的指针不是有效类型(指向指针的引用是!)因此,move
函数无效。
相关文章:
- clang:错误:链接器命令失败,退出代码为 1(使用 -v 查看调用) - 体系结构的未定义符号 x86_64:
- C++ std::vector<int> 体系结构的未定义符号 x86_64:
- C++错误 - 体系结构的未定义符号 x86_64:
- 删除此体系结构和未定义的行为
- OpenMP Mac OSX Lion c++ 链接器错误 体系结构的未定义符号 x86_64:"_omp_get_thread_num"
- 链接错误:Xcode 5 的体系结构x86_64未定义引用
- 代码块 体系结构的未定义符号 x86_64:
- 体系结构的未定义符号x86_64引用链接器错误
- 体系结构的未定义符号x86_64错误
- 体系结构的未定义符号x86_64:编译问题
- 在 Xcode 7.01 上C++ 关于 El Capitan 错误 -> 体系结构的未定义符号 x86_64:
- 使用结构体作为参数:错误:结构体未定义
- 访问结构体中定义的枚举的值
- 访问结构体中定义的枚举值
- c++位域结构体大小定义(为什么它被包装得更大?)
- 使用已定义结构体的vector到达未初始化内存
- 将结构体未排序数组中的下标向左移动
- 分配过大的堆栈结构是未定义的行为吗
- 体系结构的未定义符号x86_64:"_glutInit",引用自:_main in main.o / Netbeans on Mac
- c++中所有操作符都可以在结构体中定义