c++ - 在类构造函数中初始化一个 vector

标签 c++ vector constructor null initialization

我有一个具有私有(private)属性的类,它是一个 vector 。我在构造函数中将其初始化为 null,如下所示:

Graph(int NumberOfVertices):vertices(NumberOfVertices),             
                                    edges(0),
                                    adjacency_list(NULL){};

vector 是

std::vector<Edge *> adjacency_list;

程序不工作,但我不确定这是不是错误,是否像我正在做的那样初始化一个 vector ?

最佳答案

你没有在你的类中初始化一个空的 vector 字段, vector 的默认构造函数就足够了。但是,如果您已经知道元素的数量,则可以在构造函数中调整它的大小。

Graph(int NumberOfVertices):vertices(NumberOfVertices),             
                                    edges(0) { adjacency_list.resize(vertices)};

这绝对是不正确的:

adjacency_list(NULL) // this will evaluate to vector(0) 
                     // and your vector has 0 size

您可能混淆了 vector 存储的指针和 vector 本身。使用 NULL 初始化类 vector 将评估为大小为 0 的 vector 。 无需初始化作为类成员的空vector实例:

Default initialization is performed in three situations:

1) when a variable with automatic storage duration is declared with no initializer

2) when an object with dynamic storage duration is created by a new-expression without an initializer

3) when a base class or a non-static data member is not mentioned in a constructor initializer list and that constructor is called. <<< aha

The effects of default initialization are:

If T is a class type, the default constructor is called to provide the initial value for the new object.

If T is an array type, every element of the array is default-initialized. Otherwise, nothing is done.

If T is a const-qualified type, it must be a class type with a user-provided default constructor.

关于c++ - 在类构造函数中初始化一个 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19752522/

相关文章:

c++ - 返回指向类成员函数的指针

c++ - 使用 unique_ptr 和 vector

c++ - “如何使用 C++ 将字符串的第一个和最后一个索引返回到 vector 中?

Java:传递相同对象作为参数的对象构造函数

C++ 从指针构造

c++ - 如何在 C++ 中使用带有自定义排序成员函数的 sort()?

c++ - 诸如 bits/vector.tcc 之类的头文件名是否符合标准?

c++ - 如果没有显卡,谁来运行 OpenGL 着色器

c++ - 在模板 vector 上返回迭代器

C++为什么vector初始化会调用copy constructor