在 main 中初始化 class 的 "static const" 类型变量成员的更好方法

Better way to initialize a "static const"-type variable member of a class in the main

我有一个 class 需要一个静态常量变量成员。 class 的值将在运行时通过用户输入获知。我已经阅读了很多 post 但到目前为止 none 的解决方案有效。我知道这个 post:

包含变通方法,但它使用了一个我想避免的全局变量。而且也没有真正解决问题。

考虑一下:

#include

class A {
  friend void foo(int);
    static int dummy;
public:
    static const int &T;
};

const int &A::T = A::dummy;
int A::dummy = 0;

void foo(int val) { A::dummy = val; }

int main() {
    foo(10);
    std::cout << A::T << std::endl;
    foo(12);
    std::cout << A::T << std::endl;
}

程序会在控制台编译写入10和12。这违背了 const 限定符的目的。这里的 const 是引用而不是值。所以我得出的结论是在执行时不可能有一个static const class变量!

我知道另一种涉及创建设置类型的方法class,但它不是很整洁。

因此,如果有人知道简单的解决方案,请告诉我们!

如果您不喜欢全局变量,您可以执行以下方案:

class A {
  friend void foo(int);
    static int dummy;
public: 
    static const int &T;
};

const int &A::T = A::dummy;
int A::dummy = 0;

void foo(int val) { A::dummy = val; }

int main() {
    foo(10);
    std::cout << A::T << std::endl;
}

Live Demo

即在您的 class 中将一个辅助 static int 变量声明为私有。给朋友一个改变那个助手值的函数。

如果你只想初始化一次你可以将辅助函数更改为:

void foo(int val) { 
  static int count = 0;
  if(!count) A::dummy = val;
  ++count;
}

Live Demo

或者如果您不喜欢全局函数,您可以将上面显示的 foo 函数作为 Astatic 成员函数,如下所示:

class A {
    static int dummy;
public: 
    static const int &T;
    static void foo(int val) { A::dummy = val; }
};

const int &A::T = A::dummy;
int A::dummy = 0;

int main() {
    A::foo(10);
    std::cout << A::T << std::endl;
}

Live Demo

我在原始问题的 link 中提供的解决方案和我得到的其他解决方案中也有问题。考虑一下: #include

class A {
  friend void foo(int);
    static int dummy;
public:
    static const int &T;
};

const int &A::T = A::dummy;
int A::dummy = 0;

void foo(int val) { A::dummy = val; }

int main() {
    foo(10);
    std::cout << A::T << std::endl;
    foo(12);
    std::cout << A::T << std::endl;
}

程序会在控制台编译写入10和12。这违背了 const 限定符的目的。这里的 const 是引用而不是值。所以我得出的结论是在执行时不可能有一个 static const class 变量!