C中的不同类型的初始化

我正在学习C,对于不同类型的初始化,我感到很困惑.

你可以做:

T a;

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

你也可以做:

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

; (在某些情况下):

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

;如果没有构造函数

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

;并且:

T a = T(1,3);

.

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

T a = new T(1,3);

还有别的事吗?

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

解决方法

你犯了一些错误.我会清理它们
// Bog-standard declaration.
// Initialisation rules are a bit complex.
T a;


// WRONG - this declares a function.
T a();

// Bog-standard declaration,with constructor arguments.
// (*)
T a(1,3... args);

// Bog-standard declaration,with *one* constructor argument
// (and only if there's a matching,_non-explicit_ constructor).
// (**)
T a = 1;

// Uses aggregate initialisation,inherited from C.
// Not always possible; depends on layout of T.
T a = {1,6};

// Invoking C++0x initializer-list constructor.
T a{1,6};

// This is actually two things.
// First you create a [nameless] rvalue with three
// constructor arguments (*),then you copy-construct
// a [named] T from it (**).
T a = T(1,3);

// Heap allocation,the result of which gets stored
// in a pointer.
T* a = new T(1,3);

// Heap allocation without constructor arguments.
T* a = new T;

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...