我正在学习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;
原文地址:https://www.jb51.cc/c/113857.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。