如何在c ++中初始化静态类对象?

时间:2017-08-26 14:29:07

标签: c++ c++11

Lane.h

class Lane{
    //other declarations..
public:
    Lane(){}
    static Lane left_line;
    static Lane right_line;
};

Lane.cpp

Lane Lane::left_line;

的main.cpp

int main(){
    Lane::left_line();  //doesn't work

我做错了什么,或者我做错了什么。我真的很困惑静态对象如何正常工作。

1 个答案:

答案 0 :(得分:1)

static成员在类中声明并在类外部初始化一次。无需再次调用构造函数。我已经为您的Lane课程添加了一种方法,以使其更加清晰。

class Lane{
    //other declarations..
public:
    Lane(){}
    static Lane left_line; //<declaration
    static Lane right_line;

   void use() {};
};

<强> Lane.cpp

Lane Lane::left_line; //< initialisation, calls the default constructor of Lane

<强>的main.cpp

int main() {
  // Lane::left_line(); //< would try to call a static function called left_line which does not exist
  Lane::left_line.use(); //< just use it, it was already initialised
}

通过这样做,您可以使初始化更加明显:

Lane Lane::left_line = Lane();

在Lane.cpp。