【问题标题】:Is it possible to initialise a static member in a static method of a class in C++?是否可以在 C++ 中的类的静态方法中初始化静态成员?
【发布时间】:2020-08-05 22:48:02
【问题描述】:

所以我有一个静态成员 precision 和一个公共静态方法来在我的类中设置它的值(下面的代码被精简了很多)。

class Foo {
private:
    typedef unsigned short precision_t;
    static precision_t precision;
public:
    static void set_precision(precision_t value) {
        precision_t precision = value;
        /* other stuff */
    }
    
    static precision_t get_precision() {
        return precision;
    }
};

当我创建一个实例然后设置值时,它似乎工作正常,但尝试获取该值会产生一个略显神秘的错误:main.cpp:(.text._ZN3Foo13get_precisionEv[_ZN3Foo13get_precisionEv]+0x7): undefined reference to `Foo::precision' collect2: error: ld returned 1 exit status(在 onlinegdb.com 上运行)。

main 中的确切代码:

Foo *foo = new Foo(); //fine
foo->set_precision(5); //no error, but probably wrong given undefined reference
std::cout << Foo::get_precision(); //shows above error

set_precision 的原始代码看起来更像

static void set_precision(precision_t value) {
    static bool defined = false;
    if (defined) {
        precision = value
    } else {
        precision_t precision = value;
        defined = true;
    }
    /* other stuff */
}

所以它只会在第一次初始化precision

我还尝试对存储指向所有实例的指针的向量执行此操作,而不必编写代码以在类外部/.cpp 文件中进行初始化。

甚至有可能这样做还是我必须在.cpp 文件中在main 函数之前初始化(存储实例指针的向量和存储当前精度的无符号短整型)?

【问题讨论】:

  • 所有static 成员should be defined 在程序中只出现一次。您可以将其视为编译器的“为该对象分配静态内存的位置”-ish 指令。或者只使用static inline
  • 另外,set_precision 中的precision_t precision = value; 设置了一个本地 变量,而不是同名的静态成员变量。

标签: c++ initialization declaration static-methods static-members


【解决方案1】:

更新代码:

#include <iostream>
using namespace std;

class Foo {
private:
    typedef unsigned short precision_t;
    static inline precision_t precision; 
    //static precision_t precision; //when not using static inline
public:
    static void set_precision(precision_t value) {
        //precision_t precision = value; //<<-- error in your code
        precision = value; 
        /* other stuff */
    }
    
    static precision_t get_precision() {
        return precision;
    }
};

//Foo::precision_t Foo::precision = 0; //when not using static inline

int main() {
    Foo *foo = new Foo(); //fine
    foo->set_precision(5); //no error, but probably wrong given undefined reference
    std::cout << Foo::get_precision(); //shows above error
    return 0;
}

【讨论】:

  • 我之前自己试过了,还是不行。如果有人发现这段代码有inline的错误,看来你必须使用C++17或更高版本。 (这不是最新版本 GCC 的默认值;尝试 -std=c++17)。 MSVC 中显然存在与之相关的错误 (stackoverflow.com/questions/51276050/…)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-05-18
  • 1970-01-01
  • 2012-07-22
  • 1970-01-01
  • 2011-07-18
  • 2018-10-06
  • 1970-01-01
相关资源
最近更新 更多