如何在 c++ 中初始化静态类对象?
How to initialize static class objects in c++?
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。
相关文章:
- 如何正确实例化静态字段 tat 是另一个类对象
- 对静态分配的子类对象进行静态分配的纯虚拟父类引用是否合法?
- 如何从静态类函数初始化静态类对象
- 在 c++ 中使用字符串变量选择静态类结构,而不带对象
- (2 问题)"类"类型重新定义(即使 #pragma 一次),以及静态函数内的静态成员对象初始化?
- 类本身内部的类对象的静态constexpr数组
- 如何在 c++ 中初始化静态类对象?
- 为静态类创建指向对象的指针是否合法?
- 如何访问类对象的每个实例的静态变量值
- 静态数据成员是否在所有类对象之前初始化?
- 对我的基类对象数组使用大量的静态类型转换——这可以吗
- 指向子类对象的指针的静态数组出现问题
- C++返回模板类对象的静态非成员函数
- C - 函数能够访问类方法,而不会创建静态或对象
- 为什么可以从实例化基类对象的投射指针调用非静态派生类方法
- c++中的静态对象与单例类对象
- 如何引用类的静态私有对象
- 作为类对象容器的静态向量
- 正在初始化不使用零参数构造函数c++的静态类对象
- 静态类对象