在 C++ 中跨所有结构访问变量

Accesing variables across all struct in C++

假设有以下代码:

struct Joe {
    const double weigth = 88.6;
    const double heigth = 185.6;
    const double X = Alice().heigth; // Error: undeclared identifier.
};

struct Alice {
    const double weigth = 65.2;
    const double heigth = 179.1;
    const double X = Joe().heigth; // No issues
};

在 Alice 的结构中我可以访问 Joe 的变量,但是在 Joe 的结构中我不能访问 Alice 的参数,因为它是在 Alice 之前声明的。有什么解决办法,我不能在任何地方“google”吗?

将 X 设为静态常量,在 Joe 中声明 X 但不要在结构中初始化。 initJoe::x后定义Alice。 const double Joe::X = Alice().height;

鉴于您要求 Joe::X 必须默认初始化为 Alice().height 并且 Alice::X 必须默认初始化为 v.v,我认为不存在解决方案。 classes 的声明相互依赖,因此是循环的。

如果不要求上述变量必须默认初始化,可以在Joe.hpp中声明classJoe,声明class[=16] =] 在 Alice.hpp 中。在 Joe.cpp 中,您可以包含 Alice.hpp 并为 Joe::X 初始化 Alice::X 和 v.v。

例子Joe.hpp

#include "Joe.hpp"
#include "Alice.hpp"

Joe::Joe()
  : X(Alice().height)
{}