访问类"public"结构

Access "public" struct defined inside a class

本文关键字:结构 public 访问      更新时间:2023-10-16

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

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;
    };
};

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

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

这是因为您引入了PoseCommand类型引用,然后编译器才能在private部分中看到它们:

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;
    };
};

请参阅工作代码。

另一种方法是重新排列您的publicprivate1 部分,如 @2785528 的答案中所述。


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

还要考虑:您可以在不添加行的情况下稍微重新排列代码。

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);
};

您可能有多个私人部分。

此外,您可以考虑在类声明结束时将所有私有属性一起移动。

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

在您的情况下解决此问题的一种简单方法是将私有部分移到末尾。