構造函數

前言

C++的目標之一就是讓用戶使用類對象就像使用基本內置類型對象一樣。

對基本內置類型而言,其初始化語法如下:

#include <iostream>

using namespace std;

int main() {
    int year = 2001;
    struct person{
        double height;
        double weigth;
    };
    person xiong = {180.0 , 150.0};

    cout << "OK!!!" << endl;
}

但是對於用戶自定義類型而言,我們還無法適用常規的初始化語法:

#include <iostream>
#include <string>
#include "cmake-build-debug/Share.h"

using namespace std;

int main() {
    Share xiong;
    xiong.acquire("lenovo" , 100 , 16.6);//正確

    Share xiong = {"lenovo" , 100 , 16.6};//錯誤
}

究其原因,是因爲Share類的數據成員訪問狀態是private,意味着程序不能直接訪問數據成員,更不能給數據成員直接賦值了。

前面說過,對於private數據成員,只能通過類接口,也就是public成員函數進行訪問。所以類專門設計了一種成員函數,來對類中的private數據成員進行賦值操作,即構造函數。

構造函數的聲明

//
// Created by Administrator on 2017/3/7.
//
#ifndef PROJECT1_SHARE_H
#define PROJECT1_SHARE_H

#include <array>

using namespace std;
class Share {
private:
    string company;
    long shares;
    double share_value;
    double total_value;
    void set_total(){
            total_value = shares * share_value;
    }
public:
    Share(const string &comp , long number , double price);//構造函數的聲明
    void acquire(const string &comp , long number , double price);
    void buy(long number , double price);
    void sell(long number , double price);
    void update(double price);
    void show();
};


#endif //PROJECT1_SHARE_H

構造函數的定義

//
// Created by Administrator on 2017/3/7.
//

#include <iostream>
#include "Share.h"

Share::Share(const string &comp, long number, double price) { /*構造函數的定義*/
    company = comp;
    if (number < 0){
        cout << "The number of shares purchased can not be less than zero, the transaction canceled!" << endl;
        shares = 0;
    } else
        shares = number;
    share_value = price;
    set_total();
}

void Share::acquire(const string &comp, long number, double price) {
    company = comp;
    if (number < 0){
        cout << "The number of shares purchased can not be less than zero, the transaction canceled!" << endl;
        shares = 0;
    } else
        shares = number;
    share_value = price;
    set_total();
}

void Share::buy(long number, double price) {
    if (number < 0){
        cout << "The number of shares purchased can not be less than zero, the transaction canceled!" << endl;
    } else{
        shares += number;
        share_value = price;
        set_total();
    }
}

void Share::sell(long number, double price) {
    if (number < 0){
        cout << "The number of shares sold can not be less than zero, the transaction canceled!" << endl;
    } else if (number > shares){
        cout << "The number of shares sold can not be greater than the number of existing shares, the transaction canceled!" << endl;
    } else{
        shares -= number;
        share_value = price;
        set_total();
    }
}

void Share::update(double price) {
    share_value = price;
    set_total();
}

void Share::show() {
    cout << "Company Name: " << company << endl;
    cout << "Number of shares held:" << shares << endl;
    cout << "Stock price:" << share_value << endl;
    cout << "Total stock:" << total_value << endl;
}

可以看出構造函數和類成員函數acquire基本相同,但是區別在於:當程序聲明對象是,將自動調用構造函數。

構造函數的使用

#include <iostream>
#include <string>
#include "cmake-build-debug/Share.h"

using namespace std;

int main() {

    /*顯示調用構造函數*/
    Share xiong1 = Share("alibaba" , 100 , 50.26);
    xiong1.show();

    /*隱式調用構造函數*/
    Share xiong2("lenovo" , 100 , 25.25);
    xiong2.show();

}

C++提供了顯示和隱式兩種使用構造函數來初始化對象的方式。

運行結果

H:\Project1\cmake-build-debug\Project1.exe
Company Name: alibaba
Number of shares held:100
Stock price:50.26
Total stock:5026
Company Name: lenovo
Number of shares held:100
Stock price:25.25
Total stock:2525

Process finished with exit code 0

默認構造函數

每次創建類對象,C++都使用類構造函數初始化對象。

C++中存在一種特殊的構造函數,當沒有提供顯示的初始值時,用其來創建對象的構造函數。這就是默認構造函數。

默認構造函數聲明

Share();

可以看出,默認構造函數沒有參數。

默認構造函數定義

Share::Share() {

}

默認構造函數調用

/*調用默認構造函數*/
Share xiong3;

有一個值得注意的問題是:如果類沒有提供任何構造函數,C++將自動提供默認構造函數。但是,如果程序員爲類定義了構造函數,程序員必須爲類定義默認構造函數。如果提供了非默認構造函數,但是沒有提供默認構造函數,則諸如

Share xiong3;

會出現錯誤。

其原因在於C++希望禁止創建未初始化的對象。

另外一個值得注意的事情是,對於構造函數而言,如果我們爲每個參數值都提供了默認實參,則其實質上爲默認構造函數。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章