简体   繁体   English

C ++禁止在将结构传递给函数时声明没有任何类型错误的…

[英]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 错误:ISO C ++禁止声明无类型的“单元格”

Isn't Cell my type? 细胞不是我的类型吗?

AStarPlanner.h 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 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. Cell的声明Cell方法声明之前。

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 ). 同样,从技术上讲,没有Cell类型,但是AStarPlanner::Cell (但是它在class的上下文中自动解析)。

C++ rules about name visibility inside a class declaration are non obvious. 关于类声明中名称可见性的C ++规则并不明显。 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). 没有这个限制的技术原因(或者说更好,我不知道它可能是什么,但我从来不敢写一个完整的C ++解析器)。 This however is how the language is defined. 但是,这就是语言的定义方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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