访问在类内部定义的“公共”结构

时间:2019-03-28 18:28:42

标签: c++

我正在尝试创建一个类,该类的私有成员必须访问在同一类中通过公共访问定义的结构。我正在使用VS Code编写代码。当我尝试编写私有成员函数时,它说未定义结构标识符。

class Planner
{
  private:
    typedef std::pair<int, int> location;
    std::vector<location> obstacles;
    Pose next_state(const Pose& current_state, const Command& command);

  public:
    Planner(/* args */);
    virtual ~Planner();

    /* data */
    struct Command
    {
        unsigned char direction;
        unsigned char steering;
    };

    struct Pose
    {
        int x;
        int y;
        int theta;
    };

    struct Node
    {
        Pose pose;
        int f;
        int g;
        int h;
    };
};

在这里,它说“标识符“姿势”未定义”。我想了解这里发生了什么。

3 个答案:

答案 0 :(得分:4)

  

在这里,它说“标识符“姿势”未定义”。我想了解这里发生了什么。

那是因为您在编译器可以在Pose部分看到它们之前引入了Commandprivate类型引用:

private:
    // ...
    Pose next_state(const Pose& current_state, const Command& command);
                       // ^^^^                       ^^^^^^^

编译器在使用前需要查看标识符


解决方法是在Planner类中需要正确排序的前向声明:

class Planner {
  // <region> The following stuff in the public access section,
  // otherwise an error about "redeclared with different access" will occur.
  public:
    struct Pose;
    struct Command;
  // </region> 

  private:
    typedef std::pair<int, int> location;
    std::vector<location> obstacles;
    Pose next_state(const Pose& current_state, const Command& command);

  public:
    Planner(/* args */);
    virtual ~Planner();

    /* data */
    struct Command {
        unsigned char direction;
        unsigned char steering;
    };

    struct Pose {
        int x;
        int y;
        int theta;
    };

    struct Node {
        Pose pose;
        int f;
        int g;
        int h;
    };
};

请参见working code

另一种选择是按照@2785528's answer中所述重新排列publicprivate部分 1


1) 请注意,这些可以在类声明中多次提供。

答案 1 :(得分:2)

还请考虑:您可以稍微重新排列代码,而无需添加行。

class Planner
{
private:
   typedef std::pair<int, int> location;
   std::vector<location> obstacles;
   // "next_state" private method moved below

public:
   Planner(/* args */){};
   virtual ~Planner(){};

   /* data */
   struct Command
   {
      unsigned char direction;
      unsigned char steering;
   };

   struct Pose
   {
      int x;
      int y;
      int theta;
   };

   struct Node
   {
      Pose pose;
      int f;
      int g;
      int h;
   };

private:
   Pose next_state(const Pose& current_state, const Command& command);

};

您可能有多个私人部分。

此外,您可以考虑在类声明的末尾将所有私有属性移到一起。

答案 2 :(得分:0)

文件按顺序解析。在定义姿势之前,您要先参考姿势。您可以使用成员函数和变量来执行此操作,但这是例外,而不是规则。

要解决此问题,一种简单的方法是将私有部分移到末尾。

相关问题