使用结构体作为参数:错误:结构体未定义

Using structs as arguments: Error: Struct not defined

本文关键字:结构体 未定义 错误 参数      更新时间:2023-10-16

我正在创建一个类,其中我定义了一个名为"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

  1. 房间不能是私有的,因为你在公共成员函数中使用它。
  2. 或者像这样向前声明:

    struct Room;
    // destructor
    ~Graph();
    
  3. 或者在使用它之前在类的顶部声明并实现它

  4. void move( Room &*room , String direction ); //this is not valid C++

您必须在使用任何类型之前声明它。前向声明就足够了,因为您在同一作用域中定义了Graph::Room。然而,既然你必须定义它,我建议在第一次使用它之前把它移到某个位置。

Graph中设置Room为私有是完全合法的(但如果您的公共接口与之混淆,那么它是否合理是值得怀疑的)。

附带说明:指向引用的指针不是有效类型(指向指针的引用是!)因此,move函数无效。