[英]How to initialize static constant member using function
In a very simplified case, I have the following setup in which, I simply want to initialize a constant static member(of class foo) from functions of class A (singleton and instance are unrelated to this question): 在一个非常简化的情况下,我具有以下设置,在该设置中,我只想从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;
}
the aim is to initialize member ii using some function as above. 目的是使用上述某些函数初始化成员ii。 but it generates the following error:
但它会产生以下错误:
$ 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
could you please help me out? 你能帮我吗? will Appreciate it.
会赞赏的。
You are using getInstance
as a static function, but it's not declared static
. 您将
getInstance
用作静态函数,但未将其声明为static
。
Change the declaration of getInstance
: 更改
getInstance
的声明:
static A & getInstance() { return instance; }
Several issues with the code, but here's a full compilable sample: 代码有几个问题,但这是一个完整的可编译示例:
class A
{
public:
static A instance;
static A & getInstance() { return instance; }
int i(){ return 10;}
int j(){ return 20;}
};
class foo {
public:
static const int ii;
};
const int foo::ii = A::getInstance().i() * A::getInstance().j();
A A::instance;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.