C中的不同类型的初始化

C中的不同类型的初始化,第1张

概述我正在学习C,对于不同类型的初始化,我感到很困惑. 你可以做: T a; 据我所知,这有时会初始化一次,有时也不会,这取决于T是否有一个默认构造函数. 你也可以做: T a(); // orT a(1, 2, 3... args); ; (在某些情况下): T a = 1; // implicitly converted to T sometimes? ;如果没有构造函数: T a = {1, 我正在学习C,对于不同类型的初始化,我感到很困惑.

你可以做:

@H_419_4@T a;

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

你也可以做:

@H_419_4@T a(); // orT a(1,2,3... args);

; (在某些情况下):

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

;如果没有构造函数:

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

;并且:

@H_419_4@T a = T(1,3);

.

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

@H_419_4@T a = new T(1,3);

还有别的事吗?

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

解决方法 你犯了一些错误.我会清理它们 @H_419_4@// 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中的不同类型的初始化全部内容,希望文章能够帮你解决C中的不同类型的初始化所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/langs/1249570.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-07
下一篇2022-06-07

发表评论

登录后才能评论

评论列表(0条)

    保存