1

我有一个带有私有属性的类,它是一个向量。我在构造函数中将其初始化为 null,如下所示:

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

向量是

std::vector<Edge *> adjacency_list;

该程序不起作用,但我不确定这是错误,是否像我正在做的那样初始化一个向量?

4

2 回答 2

2

you don't initialize an empty vector field in your class, default constructor of vector suffices. You may however resize it in constructor if you know already the number of elements.

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

This is definitely incorrect:

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

probably you've confused the pointers that vector stores with the vector itself. Initializing class vector with NULL will evaluate to a vector with 0 size. There is no need to initialize an empty vector instance which is a class member:

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.

于 2013-11-03T11:44:57.613 回答
1

如果您希望向量的第一个元素使用 NULL 进行初始化,请使用以下构造函数:

explicit vector ( size_type n, const value_type& val = value_type(), const allocator_type& alloc = allocator_type() );

通过以下方式:

adjacency_list( 1, NULL )
于 2013-11-03T12:18:40.843 回答