gpt4 book ai didi

c++ - 使用结构作为参数 : Error: Struct not defined

转载 作者:行者123 更新时间:2023-11-30 01:27:44 25 4
gpt4 key购买 nike

我正在创建一个类,我在其中定义了一个名为“Room”的结构,我在头文件中将其声明为私有(private)。我有几个公共(public)函数需要一个“房间”作为参数。当我编译(在 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: header 的情况下编译得很好。你为什么有这个?结构是否在类内部声明?

编辑

在声明之前您已经使用过 Room:

const Room * findRoom( int roomNumber );

此外,您不能通过已声明的公共(public)方法返回 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 部分之上。

关于c++ - 使用结构作为参数 : Error: Struct not defined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8461541/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com