C中的不同类型的初始化

前端之家收集整理的这篇文章主要介绍了C中的不同类型的初始化前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在学习C,对于不同类型的初始化,我感到很困惑.

你可以做:

  1. T a;

据我所知,这有时会初始化一次,有时也不会,这取决于T是否有一个默认构造函数.

你也可以做:

  1. T a(); // or
  2. T a(1,2,3... args);

; (在某些情况下):

  1. T a = 1; // implicitly converted to T sometimes?

;如果没有构造函数

  1. T a = {1,3,4,5,6};

;并且:

  1. T a = T(1,3);

.

如果你想在堆上分配,那就是

  1. T a = new T(1,3);

还有别的事吗?

我想知道是否a)我已经有所有类型的初始化覆盖和b)何时使用每种类型?

解决方法

你犯了一些错误.我会清理它们
  1. // Bog-standard declaration.
  2. // Initialisation rules are a bit complex.
  3. T a;
  4.  
  5.  
  6. // WRONG - this declares a function.
  7. T a();
  8.  
  9. // Bog-standard declaration,with constructor arguments.
  10. // (*)
  11. T a(1,3... args);
  12.  
  13. // Bog-standard declaration,with *one* constructor argument
  14. // (and only if there's a matching,_non-explicit_ constructor).
  15. // (**)
  16. T a = 1;
  17.  
  18. // Uses aggregate initialisation,inherited from C.
  19. // Not always possible; depends on layout of T.
  20. T a = {1,6};
  21.  
  22. // Invoking C++0x initializer-list constructor.
  23. T a{1,6};
  24.  
  25. // This is actually two things.
  26. // First you create a [nameless] rvalue with three
  27. // constructor arguments (*),then you copy-construct
  28. // a [named] T from it (**).
  29. T a = T(1,3);
  30.  
  31. // Heap allocation,the result of which gets stored
  32. // in a pointer.
  33. T* a = new T(1,3);
  34.  
  35. // Heap allocation without constructor arguments.
  36. T* a = new T;

猜你在找的C&C++相关文章