私有静态 Constexpr 成员变量在 Main 中无法访问?

Private Static Constexpr Member Variable is Inaccessible in Main?

在我的环境中class我有一个私有静态成员变量:

class Environment {
public:
    Environment(double air_density, Color background_color);

    void create_new(const Part &object);

    double get_air_density() const noexcept;
    void set_air_density() noexcept;

    Color get_background_color() const noexcept;
    void set_background_color() noexcept;

    std::vector<Part> get_objects() const noexcept;
    void set_objects() noexcept;

private:
    std::vector<Part> objects;
    Color background_color;
    
    //ERROR:
    static constexpr Color default_background_color = Color({ 210, 210, 210 });
};

主要是我试图访问该变量:

int main() {
    Environment environment(0.1, Environment::default_background_color); // ERROR: 'member "Environment::default_background_color" is inaccessible' 

    Part part(10, 10, 50, 50, false, 0, true);
    environment.create_new(part);

    while (running) {
        part.update_position(0.1);

        background(141, 3, 255);
        part.draw();


        render(dc);
    }
}

所以我的问题是,哪里出了问题以及如何创建一个可以在环境之外访问的 const 静态变量 class?

您的数据成员被声明为 private(而不是 static,顺便说一句),因此 class.

之外的任何代码都无法访问它

如果您希望main()访问该成员,可以:

  • 将成员声明为 public(和 static):
class Environment {
public:
    Environment(double air_density, Color background_color);
    ...
    static constexpr Color default_background_color = Color({ 210, 210, 210 });
    ...
};
int main() {
    Environment environment(0.1, Environment::default_background_color); // OK
    ...
}

Online Demo

  • 声明 main() 作为 class 的 friend:
class Environment {
public:
    Environment(double air_density, Color background_color);
    ...
private:
    ...
    static constexpr Color default_background_color = Color({ 210, 210, 210 });

    friend int main();
};
int main() {
    Environment environment(0.1, Environment::default_background_color); // OK
    ...
}

Online Demo