How to get the default value of any type

后端 未结 4 1680
难免孤独
难免孤独 2021-02-08 07:47

In C# I can write something like this:

    class AnyThing
    {
        static public T Default = default(T);
    }

    static void Main ()
    {
              


        
4条回答
  •  误落风尘
    2021-02-08 08:17

    In C++ there is no something like default keyword in C#. Since initialization by default constructor of value of class-type will be failed, if default constructor is private. In C#, if default constructor is private, value of class-type will be initialized to null, since class-type is reference-type.

    Initialition by {} is defined by language specification. It's C++11. In C++03 you should use

    T obj = T();
    

    As pointed by bames53 in comment, when you want to initialize T* you should use

    before C++11.

    T* obj = 0;
    

    or

    T* obj = NULL;
    

    in C++11.

    T* obj = {};
    

    or

    T* obj = nullptr;
    

提交回复
热议问题