简体   繁体   中英

C++ forbids declaration of … with no type error while passing a struct to a function

I can't figure out what I am doing wrong here.
I want to sort a list and have a compare function to sort it.
Found a code example where exactly my problem was solved but it doesn't work for me.

I always get this error:
error: ISO C++ forbids declaration of 'Cell' with no type

Isn't Cell my type?

AStarPlanner.h

class AStarPlanner {

public:

  AStarPlanner();

  virtual ~AStarPlanner();

protected:

  bool compare(const Cell& first, const Cell& second);

  struct Cell {

        int x_;
        int y_;
        int f_;   // f = g + h
        int g_;   // g = cost so far
        int h_;   // h = predicted extra cost

        Cell(int x, int y, int g, int h) : x_(x), y_(y), g_(g), h_(h) {
                f_ = g_ + h_;
        }
  };

};

AStarPlanner.cpp

 bool AStarPlanner::compare(const Cell& first, const Cell& second)
 {
    if (first.f_ < second.f_)
       return true;
    else
       return false;
 }

Move the declaration of Cell before the method declaration.

class AStarPlanner {
public:
  AStarPlanner();
  virtual ~AStarPlanner();
protected:
  struct Cell {
        int x_;
        int y_;
        int f_;   // f = g + h
        int g_;   // g = cost so far
        int h_;   // h = predicted extra cost
        Cell(int x, int y, int g, int h) : x_(x), y_(y), g_(g), h_(h) {
                f_ = g_ + h_;
        }
  };
  bool compare(const Cell& first, const Cell& second);
};

Also, technically, there's no Cell type, but AStarPlanner::Cell (but it's resolved automatically in the context of the class ).

C++ rules about name visibility inside a class declaration are non obvious. For example you can have a method implementation referring to a member even if the member is declared later in the class... but you cannot have a method declaration referencing a nested type if the type is declared later.

Moving the nested type declarations at the beginning of the class solves the problem in your case.

There is no technical reason for for this limitation (or to say it better I don't see what it could be, but I never dared writing a full C++ parser). This however is how the language is defined.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM