我有一个具有私有(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/