[英]How to initialize static class objects in c++?
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
我做错了还是我做错了什么。 我实际上对静态对象的工作方式感到困惑。
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中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.