[英]Access “public” struct defined inside a class
我正在嘗試創建一個類,該類的私有成員必須訪問在同一類中通過公共訪問定義的結構。 我正在使用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;
};
};
在這里,它說“標識符“姿勢”未定義”。 我想了解這里發生了什么。
在這里,它說“標識符“姿勢”未定義”。 我想了解這里發生了什么。
那是因為您在編譯器可以在private
部分看到它們之前引入了Pose
和Command
類型引用:
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;
};
};
請參閱工作代碼 。
另一種方法是按照@ 2785528的答案中所述重新安排您的public
和private
部分1 。
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);
};
您可能有多個私人部分。
同樣,您可以考慮在類聲明的末尾將所有私有屬性一起移動。
文件按順序解析。 在定義姿勢之前,您要先參考姿勢。 您可以使用成員函數和變量來執行此操作,但這些是例外,而不是規則。
解決此問題的一種簡單方法是將專用部分移到末尾。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.