1. 程式人生 > >C++使用構造器初始化物件的兩種方式

C++使用構造器初始化物件的兩種方式

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()方法

然而,你不能使用物件來呼叫結構器,因為在結構器完成物件生成之前,是沒有物件的。結構器不是用來被物件引用,它是用來建立物件。