类字段构造函数调用? [英] class fields constructor called?

查看:61
本文介绍了类字段构造函数调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我在某处读到过:在创建类实例时,会调用其字段的默认构造函数。这是真的?我有点测试它,似乎没有工作。



特别是,如果我上课:



  class  Car 
{

公共

卡车;

Car()
{
// 基本上什么都不做/ span>
}

}





调用以下代码,自动调用Truck的构造函数?

汽车; 





即使卡车定义为指针,例如



  class  Car 
{

public

卡车*卡车;

Car()
{
// 基本上什么都不做/ span>
}

}

解决方案

在第一种情况下, Truck 没有参数的构造函数(默认构造函数)隐式调用成员 truck

In在指针的情况下,指针保持未初始化状态。原因:任何指针都是基本类型(如 int char 等),因此,不是初始化除非明确告知这样做(例如在 Car 构造函数的初始化列表中)。

干杯

Andi

Hi,
I''ve read this somewhere:"When making a class instance, the default constructor of its fields are invoked". Is this true? I was kind of testing it, doesn''t seem to work.

particularly, if I have class:

class Car
{

public:

Truck truck;

Car()
{
// do nothing basically
}

}



does calling following code, automatically invoke constructor of Truck?

Car car;



Even if truck is defined as a pointer, e.g.

class Car
{

public:

Truck* truck;

Car()
{
// do nothing basically
}

}

解决方案

In the first case, the Truck constructor with no parameter (the default constructor) is implicitly called for the member truck.
In the pointer case, the pointer remains uninitialized. Reason: any pointer is a basic type (like an int, char, etc.), and thus, is not initialized unless explicitly told to do so (e.g. in the initializer list of a Car constructor).
Cheers
Andi


这篇关于类字段构造函数调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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