1

我在 Stack.h 中编写了以下代码:

class Stack{
public:
    inline bool full();
    int size();
    inline bool empty();
    bool push(const string&);
    bool pop(string &s);
    bool peek(string &s);
    virtual void print();
    virtual ~Stack(){}

protected:
    vector<string> _elem;
    int const _maxsize=10;    // line X
};

我得到了错误:

Stack.h:14: error: ISO C++ forbids initialization of member ‘_maxsize’
Stack.h:14: error: making ‘_maxsize’ static
make: *** [Stack.o] Error 1

如果我在 X 行添加一个 static 关键字,并在类定义之外初始化变量,它可能没问题。

但我的问题是,有没有可能的方法来声明一个非静态的 const 变量并仍然成功地初始化它???

4

3 回答 3

2

是的,在你的构造函数中初始化它

const int NumItems;

Foo::Foo():
NumItems(15)
{
//....
}
于 2012-11-19T18:50:50.700 回答
1

您可以使用enum

class C {
  protected:
    enum { var = 10 }; 
}

在这种情况下, C::var 将是编译时常量,甚至可以在模板中使用。

此外,c++11 允许您尝试使用的声明。

于 2012-11-19T18:53:11.987 回答
1

这在 C++11 中有效。在 C++03 中,您必须在构造函数中对其进行初始化。或者,在 C++11 中:

class Stack{
    int const _maxsize{10};
};
于 2012-11-19T18:50:24.320 回答