2017-08-26 40 views
0

Lane.h如何在C++中初始化靜態類對象?

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 

我在做什麼錯還是我做的一切錯誤。我實際上對靜態對象如何正確工作感到困惑。

+0

向我們顯示錯誤消息。 –

+0

@BrianRodriguez「沒有適當的操作符()或沒有適當的操作符的類型對象的調用」或指向函數類型的轉換函數「 – Schiphyreon

+0

@Mat我試圖通過構造函數初始化left_line對象。 – Schiphyreon

回答

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。

+0

編輯:但我可以初始化它在主要功能? – Schiphyreon

+0

編號靜態初始化發生在main被調用之前。 – muXXmit2X