简体   繁体   English

如何在C ++中初始化类中的非静态const变量?

[英]how to initialize a non-static const variable in class in C++?

I wrote these following codes in Stack.h: 我在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
};

I got the error: 我收到了错误:

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

if I add a static keyword at line X, and initialize the variable outside the class definition, it could be OK. 如果我在第X行添加一个静态关键字,并在类定义之外初始化变量,那就可以了。

But my question is that is there any possible way to declare a non-static const variable and still successfully initialize it??? 但我的问题是,是否有任何可能的方法来声明一个非静态const变量并仍然成功初始化它?

Yes, initialize this in your constructor 是的,在构造函数中初始化它

const int NumItems;

Foo::Foo():
NumItems(15)
{
//....
}

This is valid in C++11. 这在C ++ 11中有效。 In C++03 you'll have to initialize it in the constructor. 在C ++ 03中,你必须在构造函数中初始化它。 Alternitively, in C++11: 或者,在C ++ 11中:

class Stack{
    int const _maxsize{10};
};

You can use enum 你可以使用enum

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

In this case C::var will be compile-time constant, that can be even used in a template. 在这种情况下,C :: var将是编译时常量,甚至可以在模板中使用。

Also, c++11 allows the declaration you're trying to use. 此外,c ++ 11允许您尝试使用的声明。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM