访问类"public"结构
Access "public" struct defined inside a class
我正在尝试创建一个类,其私有成员必须访问在同一类中用公共访问权限定义的结构。我正在使用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;
};
};
在这里,它说"标识符"姿势"未定义"。我想了解这里发生了什么。
在这里,它说"标识符"姿势"未定义"。我想了解这里发生了什么。
这是因为您引入了Pose
和Command
类型引用,然后编译器才能在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;
};
};
请参阅工作代码。
另一种方法是重新排列您的public
并private
第1 部分,如 @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);
};
您可能有多个私人部分。
此外,您可以考虑在类声明结束时将所有私有属性一起移动。
文件按顺序解析。在定义姿势之前,您正在引用它。您可以使用成员函数和变量执行此操作,但这些是例外而不是规则。
在您的情况下解决此问题的一种简单方法是将私有部分移到末尾。
相关文章:
- 如何循环打印顶点结构
- 通过方法访问结构
- 使用不带参数的函数访问结构元素
- 预处理器:插入结构名称中的前一个行号
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 孤立代码块在结构中引发异常
- 有什么方法可以遍历结构吗
- 如何在 C# 中映射双 C 结构指针?
- 如何在C++中使用结构生成映射
- 无法将结构注册为增强几何体3D点
- 多成员Constexpr结构初始化
- C++将文本文件中的数据读取到结构数组中
- 如何重构类层次结构以避免菱形问题
- 如何在C++中序列化结构数据
- std::vector的包装器,使数组的结构看起来像结构的数组
- 没有为自己的结构调用列表推回方法
- 奇怪的结构&GCC&clang(void*返回类型)
- 在 c++ 中拥有一组结构的正确方法是什么?
- vscode g++链路故障:体系结构x86_64的未定义符号
- 访问类"public"结构