[英]C++ Setter member function with const reference causes "read access violation" exception at run-time
[英]C++ Assign a const value at run-time?
我有一个在运行时期间永远不会改变的常量值,但直到运行时才能知道。
有没有办法在不定义常量的情况下声明一个常量(或者作为一个类的成员),并且还可以确定一次(并且只有一次)计算一个计算值; 或者我将不得不求助于非const声明并使用编码S&P( ALL_CAPS
变量名称,如果在类中的static
声明等)来尝试阻止它变化?
澄清:
虽然这些都是很好的答案,但我所拥有的现实情况更为复杂:
该程序有一个主循环,在处理和渲染之间不断运行; 用户可以设置所需的选项,一旦设置它们,它们将永远不会改变,直到程序重新启动。 为主循环之前可以确定的任何内容设置“初始化”功能,但是必须在处理阶段期间在循环的中间执行依赖于用户交互的值。 (目前,我想到了持久的数据存储技术......)
像这样的东西?
const int x = calcConstant();
如果它是类成员,那么使用构造函数初始化列表,如Yuushi的答案。
您可以在struct
或class
定义它并使用初始化列表:
#include <iostream>
struct has_const_member
{
const int x;
has_const_member(int x_)
: x(x_)
{ }
};
int main()
{
int foo = 0;
std::cin >> foo;
has_const_member h(foo);
std::cout << h.x << "\n";
return 0;
}
作为静态或函数局部变量:
const int x = calcConstant();
作为班级成员:
struct ConstContainer {
ConstContainer(int x) : x(x) {}
const int x;
};
是的,您可以使用初始化方法和gettor方法创建私有静态单例字段。 以下是如何执行此操作的示例:
// In foo.h
class Foo
{
public:
// Caller must ensure that initializeGlobalValue
// was already called.
static int getGlobalValue() {
if (!initialized) {
... handle the error ...
}
return global_value;
}
static void initializeGlobalValue(...)
private:
static bool initialized;
static int global_value;
};
// In foo.cpp
bool Foo::initialized = false;
int Foo::global_value;
void Foo::initializeGlobalValue(...) {
if (initialized) {
...handle the error...
}
global_value = ...;
initialized = true;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.