榛栗栗栗子 2022-03-23 17:28 采纳率: 100%
浏览 33
已结题

C++ 静态成员类的内初始化的问题

学习 C++ Primer ,遇到点不解的问题

示例代码:

class Account
{
    //......
private:
    static constexpr int period = 30;
    double daily_tbl[period];
};

“如果某个静态成员的应用场景仅限于编译器可以替换它的值的情况,则一个初始化的const或constexpr static 不需要分别定义。相反,如果我们将它用于值不能替换的场景中,则该成员必须有一条定义语句。”
“例如,如果period的唯一用途就是定义daily_tbl的维度,则不需要在Account外面专门定义period。此时,如果我们忽略了这条定义,那么对程序非常微小的改动也可能造成编译错误,因为程序找不到该成员的定义语句。举个例子当需要把Account::period传递给一个接受const int&的函数时,必须定义period”

就是对上面两端内容不是很理解,我也试验了一下给一个静态成员数据内类初始值后,不在类外再次定义,把它作为参数给其它函数,并没有引发错误。

#include<iostream>
using namespace std;

void print(const int& p)
{
    cout << p << endl;
}

class A
{
public:
    static constexpr int a = 2;
};

//constexpr double A::a;


int main()
{
    cout << A::a << endl;
    print(A::a);

    return 0;
}

是否可以举个简单的例子,说明一下 不在类外再次定义给了类内初始值的静态成员数据 会导致的问题吗?

  • 写回答

2条回答 默认 最新

  • _GX_ 2022-03-23 17:58
    关注

    如果静态成员常量被ODR使用,比如取地址或引用,那么该静态成员常量还必须在类外定义一次。
    C++17引入了inline static data member概念,inline static data member不需要在类外定义,constexpr隐式包含inline

    struct X
    {
        static const int n = 1;
        static constexpr int m = 4;
    };
     
    const int *p = &X::n, *q = &X::m; // X::n and X::m are odr-used
    const int X::n;             // … so a definition is necessary
    constexpr int X::m;         // … (except for X::m in C++17)
    

    https://en.cppreference.com/w/cpp/language/static#Constant_static_members

    If a const non-inline (since C++17) static data member or a constexpr static data member (since C++11)(until C++17) is odr-used, a definition at namespace scope is still required, but it cannot have an initializer. A definition may be provided even though redundant (since C++17).

    https://en.cppreference.com/w/cpp/language/inline
    Since C++17

    The inline specifier, when used in a decl-specifier-seq of a variable with static storage duration (static class member or namespace-scope variable), declares the variable to be an inline variable.
    A static member variable (but not a namespace-scope variable) declared constexpr is implicitly an inline variable.

    https://en.cppreference.com/w/cpp/language/static#Static_data_members
    Since C++17

    A static data member may be declared inline. An inline static data member can be defined in the class definition and may specify an initializer. It does not need an out-of-class definition:

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 3月31日
  • 已采纳回答 3月23日
  • 创建了问题 3月23日

悬赏问题

  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体