简体   繁体   中英

Template Parameter in C++

  template <class Object>
        class ListNode
        {   
            ListNode( const Object & theElement = Object( ), ListNode * n = NULL )
              : element( theElement ), next( n ) { }

            Object   element;
            ListNode *next;

            friend class List<Object>;
            friend class ListItr<Object>;
       };

Hi everyone, I am writing a program for my data structures class and I am supposed to use this .h header file included by my instructor. To my knowledge, Object is a template parameter. Can someone please explain why there are parentheses after Object in the ListNode constructor?

Thankyou!

Essentially, it is a call to the default constructor of the Object class which was provided as a template parameter. This default constructed object is used as the default argument value for the first parameter of the ListNode constructor.

That's actually a lie, but it's simple to understand and covers most cases, so I put it at the top. In reality, it is a value initialization of an object of type Object . In the case that Object is a class with user defined constructors, value initialization is a call to the default constructor. In the case that Object is a class without user defined constructors, value initialization is (recursively) defined as value initialization of all the members. And finally, in the case of primitives (int, double, pointers, etc...), value initialization is initialization to zero.

这意味着,如果您创建不带参数参数的ListNode对象, theElement使用Object类型默认构造函数自动创建theElement参数。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM