构造函数

本文介绍了C++中的构造函数,包括构造函数的作用、声明、定义和使用方式。构造函数用于初始化类对象的private数据成员,并且存在默认构造函数,当没有提供显示的初始值时,会自动调用。如果没有定义默认构造函数,而类中定义了其他构造函数,会导致无法创建未初始化的对象。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言

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++希望禁止创建未初始化的对象。

另外一个值得注意的事情是,对于构造函数而言,如果我们为每个参数值都提供了默认实参,则其实质上为默认构造函数。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值