不同类型的C ++初始化 [英] different types of initialization in C++

查看:96
本文介绍了不同类型的C ++初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习C ++,对于不同类型的初始化非常困惑。

I'm learning C++, and am rather confused as to the different types of initialization.

您可以:

T a;

尽管我可以告诉,有时会初始化 code>有时不会,取决于 T 是否有默认构造函数。

which, as far as I can tell, will sometimes initialize a and sometimes won't, depending on if T has a default constructor.

也执行:

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

; (在某些情况下):

; (in some cases):

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

;如果没有构造函数:

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

;以及:

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

在堆上,有

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

还有什么吗?

'd喜欢知道a)我有所有类型的初始化覆盖和b)什么时候使用每种类型?

I'd like to know if a) I've got all the types of initialization covered and b) when to use each type?

推荐答案

你犯了几个错误。我会清除它们。

You made a few mistakes. I'll clear them up.

// 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, 2, 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, 2, 3, 4, 5, 6};

// Invoking C++0x initializer-list constructor.
T a{1, 2, 3, 4, 5, 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, 2, 3);

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

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

这篇关于不同类型的C ++初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆