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

How to initialize static class objects in c++?

本文关键字:静态类 对象 初始化 c++      更新时间:2023-10-16

Lane.h

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

车道.cpp

Lane Lane::left_line;

主.cpp

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

我做错了什么,或者我做错了一切。我实际上对静态对象的确切工作方式感到困惑。

static

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

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

车道.cpp

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

主.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();

在莱恩.cpp。