C中的不同类型的初始化
发布时间:2020-12-16 05:44:45 所属栏目:百科 来源:网络整理
导读:我正在学习C,对于不同类型的初始化,我感到很困惑. 你可以做: T a; 据我所知,这有时会初始化一次,有时也不会,这取决于T是否有一个默认构造函数. 你也可以做: T a(); // orT a(1,2,3... args); ; (在某些情况下): T a = 1; // implicitly converted to T so
我正在学习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; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |