2

What is the main different of these 2 and why doesn't the second one work when like this?

template <class T> MyStack<T>::Node::Node(T& input, Node* head):next(head),value(input) {}

template <class T> MyStack<T>::Node::Node(T& input, Node* head) {next = head; value = input;}

My guess on why the second one doesn't work, is because it has nothing to assign variable when initializing.

4

2 回答 2

1

MyStack<T>::value looks like it is of type T&. If that's the case, then remember that references must be initialized, and they cannot be rebound to a different object. Using the initializer list is the only way to correctly initialize references that are object data members; you cannot initialize them with assignment in the constructor. (In fact, if you omit the initializer list entry you should get some error similar to "uninitialized reference member.")

于 2013-04-09T15:25:01.110 回答
0

next and value might not have empty default constructors.

Besides that, const and reference members must be initialized in the initialization list, you can't assign to them.

于 2013-04-09T15:23:09.147 回答