2

在一个非常简化的情况下,我有以下设置,我只是想从 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

你能帮帮我吗?会欣赏它。

4

2 回答 2

2

您正在使用getInstance作为静态函数,但它没有被声明static

更改声明getInstance

static A & getInstance() { return instance; }
于 2012-05-31T09:50:12.550 回答
2

代码有几个问题,但这里有一个完整的可编译示例:

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;
于 2012-05-31T09:52:07.593 回答