Syntax error when initializing a static variable

2019-05-14 12:52发布

问题:

There are two classes defined..

    class Dictionary
    {
    public:
        Dictionary();
        Dictionary(int i);
// ...
    };

and

    class Equation
    {
        static Dictionary operator_list(1);
// ...

    };

but the problem is, whenever I compile this, I get a weird error message

error C2059: syntax error : 'constant'

But it compiles well when I use the default constructor on operator_list.

回答1:

In C++ you cannot combine declaration and initialization. When you do not specify constructor parameters of operator_list, you do not call its default constructor: you simply declare it. You need to also initialize it in the corresponding C++ file, like this:

Equation.h

class Equation {
    static Dictionary operator_list;
};

Equation.cpp:

Dictionary Equation::operator_list(1);

Note the absence of static in the CPP file: it is not there by design. The compiler already knows from the declaration that operator_list is static.

Edit: You have a choice with static constant members of integral and enumerated types: you can initialize them in the CPP file as in the example above, or you can give them a value in the header. You still need to define that member in your C++ file, but you must not give it a value at the definition time.



回答2:

static Dictionary operator_list(); is a function signature declaring a function returning a Dictionary and taking no arguments, that's why your compiler let you do it.

The reasons static Dictionary operator_list(1); fails is because you can't set a value of an complex type in the declaration of your classes. You need to do this elsewhere (e.g. in the .cpp )

For more information, see this post : https://stackoverflow.com/a/3792427/103916



回答3:

#include <iostream>
using namespace std;

class Dictionary
{
public:
    Dictionary() {}
    Dictionary(int i):page(i) {}
    void display() { cout << "page is " << page << endl; }
private:
    int page;
};

class Equation
{
    public:
    static Dictionary operator_list;

};

Dictionary Equation::operator_list(1); // static members must be initialized this way...

int main()
{
Equation::operator_list.display();
}

Output is:

page is 1