C++使用构造器初始化对象的两种方式

来源:互联网 发布:软件项目管理模板 编辑:程序博客网 时间:2024/06/07 13:42
Using Constructors

C++ provides two ways to initialize an object by using a constructor.

The first is to call the constructor explicitly:

Stock food = Stock("World Cabbage", 250, 1.25);

This sets the company member of the food object to the string "World Cabbage", the shares member to 250, and so on.

The second way is to call the constructor implicitly:

Stock garment("Furry Mason", 50, 2.5);

This more compact form is equivalent to the following explicit call:

Stock garment = Stock("Furry Mason", 50, 2.5);
C++ uses a class constructor whenever you create an object of that class, even when you use new for dynamic memory allocation. Here’s how to use the constructor with new:

Stock *pstock = new Stock("Electroshock Games", 18, 19.0);

This statement creates a Stock object, initializes it to the values provided by the arguments, and assigns the address of the object to the pstock pointer. In this case, the object doesn’t have a name, but you can use the pointer to manage the object.We’ll discuss pointers to objects further in Chapter 11.

Constructors are used differently from the other class methods. Normally, you use an object to invoke a method:

stock1.show(); // stock1 object invokes show() method

However, you can’t use an object to invoke a constructor because until the constructor finishes its work of making the object, there is no object. Rather than being invokedby an object, the constructor is used to create the object.


使用构造函数

C++提供两种方式通过构造器来初始化对象。


第一种是显式调用构造器:

Stock food = Stock("World Cabbage", 250, 1.25);

设置food对象的公司成员为字符串"world Cabbage",共享成员是250,等等。


第2种是隐式调用构造器:

Stock garment("Furry Mason", 50, 2.5);

上述紧凑形式相当于显式调用:

Stock garment = Stock("Furry Mason", 50, 2.5);

无论你在什么时候创建一个类的对象,甚至在你使用new动态分配内存时,C++都会使用类构造器。这里使用new和构造器如下:

Stock *pstock = new Stock("Electroshock Games", 18, 19.0);

上述语句创建一个Stock对象,使用提供的参数进行值初始化,并把对象的地址赋给pstock指针。这种情况,对象没有名字,但是你可以使用指针管理对象。

构造器的使用和其他类函数是不同的。通常,你使用一个对象来调用一个方法:

stock1.show(); // stock1 对象引用show()方法

然而,你不能使用对象来调用结构器,因为在结构器完成对象生成之前,是没有对象的。结构器不是用来被对象引用,它是用来创建对象。

1 0
原创粉丝点击