如何声明涉及一些简单计算的类的静态常量成员变量?

tuz*_*zer 10 c++ static const class

我试图让一个静态const成员变量与一个类中的另一个静态const变量相关.动机是如果我需要稍后修改一个值(编码时),我不需要逐个更改所有彼此相关的值.

例如:

class Box
{
    public:
        Box();
    private:
        static const double height = 10.0;
        static const double lid_height = 0.5 + height;
};
Run Code Online (Sandbox Code Playgroud)

它不会编译,错误是"Box :: height"不能出现在常量表达式中.所以我猜你必须输入一个静态const成员的值.但是有没有办法让一个成员与同一个类的另一个成员变量相关,因为它们都是静态const?

小智 19

使用以下语法在类声明之外设置静态const成员变量的值.

// box.h
#pragma once

class box
{
public:
static const float x;   
};

const float box::x = 1.0f;
Run Code Online (Sandbox Code Playgroud)

  • 疯了吧!为什么语言会阻止静态const变量在类中初始化?和doe x没有全球独家新闻? (3认同)

ken*_*ytm 10

在C++ 11中,您可以使用constexpr:

class box
{
    public:
        box();
    private:
        static constexpr double height = 10.0;
        static constexpr double lid_height = 0.5 + height;
};
Run Code Online (Sandbox Code Playgroud)

否则,你可以使用内联函数(但你需要使用它作为box::lid_height()),一个好的优化器应该能够在使用时将它减少为常量:

class box
{
    public:
        box();
    private:
        static const double height = 10.0;
        static double lid_height() { return 0.5 + height; }
};
Run Code Online (Sandbox Code Playgroud)