在一个非常简化的情况下,我有以下设置,我只是想从 A 类的函数初始化一个常量静态成员(类 foo)(单例和实例与这个问题无关):
class A
{
public:
static A instance;
A & getInstance() { return instance; }
int i(){ return 10;}
int j(){ return 20;}
};
class foo {
public:
static const int ii = A::getInstance().i() * A::getInstance().j();
};
const int foo::ii;
int main()
{
foo f;
return 1;
}
目的是使用上述某些函数初始化成员 ii。但它会产生以下错误:
$ c++ static_constant.cpp
static_constant.cpp:14:30: error: ‘A::getInstance()’ cannot appear in a constant-expression
static_constant.cpp:14:42: error: a function call cannot appear in a constant-expression
static_constant.cpp:14:44: error: ‘.’ cannot appear in a constant-expression
static_constant.cpp:14:46: error: a function call cannot appear in a constant-expression
static_constant.cpp:14:53: error: ‘A::getInstance()’ cannot appear in a constant-expression
static_constant.cpp:14:65: error: a function call cannot appear in a constant-expression
static_constant.cpp:14:67: error: ‘.’ cannot appear in a constant-expression
static_constant.cpp:14:69: error: a function call cannot appear in a constant-expression
你能帮帮我吗?会欣赏它。