C++淺析構(gòu)造函數(shù)的特性
構(gòu)造函數(shù)的概念
構(gòu)造函數(shù)是一個特殊的成員函數(shù),名字與類名相同,創(chuàng)建類類型對象時由編譯器自動調(diào)用,保證每個數(shù)據(jù)成員都有一個合適的初始值,并且在對象的生命周期內(nèi)只調(diào)用一次。
構(gòu)造函數(shù)的特性
(1)函數(shù)名與類名相同。
(2)無返回值。
(3)編譯器自動調(diào)用對應(yīng)的構(gòu)造函數(shù)。
(4)構(gòu)造函數(shù)可以重載。
我們這里直接舉一個例子
#include<iostream>
using namespace std;
class Data
{
public:
Data()
{
cout << "Date()" << this << endl;
}
void InitData(int year = 1, int month = 1, int day = 1)
{
_year = year;
_month = month;
_day = day;
}
void PrintfData()
{
cout << _year << "/" << _month << "/" << _day << endl;
}
private:
int _year;
int _month;
int _day;
};
int main()
{
Data d1,d2;
d1.InitData(2022,5,21);
d1.PrintfData();
return 0;
}
于是得到的的結(jié)果為:

只能有一個構(gòu)造函數(shù)
無參的構(gòu)造函數(shù)和全缺省的構(gòu)造函數(shù)都稱為默認構(gòu)造函數(shù),并且默認構(gòu)造函數(shù)只能有一個。
下面舉一個錯誤案例:
#include<iostream>
using namespace std;
class Data
{
public:
Data()
{
cout << "Date()" << this << endl;
}
Data()
{
_year = year;
_month = month;
_day = day;
}
void InitData(int year = 1, int month = 1, int day = 1)
{
_year = year;
_month = month;
_day = day;
}
void PrintfData()
{
cout << _year << "/" << _month << "/" << _day << endl;
}
private:
int _year;
int _month;
int _day;
};
int main()
{
Data d1
return 0;
}
上面的代碼中,有兩個默認的構(gòu)造函數(shù),因為不帶參數(shù)的構(gòu)造函數(shù)和全缺省的構(gòu)造函數(shù)都被看為默認的構(gòu)造函數(shù),所以說,現(xiàn)在有兩個構(gòu)造函數(shù),編譯器不知道到底要去調(diào)用哪個構(gòu)造函數(shù),所以說,就會報錯,所以我們刪除一個就可以了。
關(guān)于編譯器生成的默認成員函數(shù),很多人會有疑惑:在我們不實現(xiàn)構(gòu)造函數(shù)的情況下,編譯器會生成默認的構(gòu)造函數(shù)。但是看起來默認構(gòu)造函數(shù)又沒什么用?對象調(diào)用了編譯器生成的默認構(gòu)造函數(shù),但是對象year/month/_day,依舊是隨機值。也就說在這里編譯器生成的默認構(gòu)造函數(shù)并沒有什么用?
解答:C++把類型分成內(nèi)置類型(基本類型)和自定義類型。內(nèi)置類型就是語法已經(jīng)定義好的類型:如int/char...,自定義類型就是我們使用class/struct/union自己定義的類型,看看下面的程序,就發(fā)發(fā)現(xiàn)編譯器生成默認的構(gòu)造函數(shù)會對自定類型成員_t調(diào)用的它的默認成員函數(shù)
class Time
{
public:
Time()
{
cout << "Time()" << endl;
_hour = 0;
_minute = 0;
_second = 0;
}
private:
int _hour;
int _minute;
int _second;
};
class Date
{
private:
// 基本類型(內(nèi)置類型)
int _year;
int _month;
int _day;
// 自定義類型
Time _t;
};
int main()
{
Date d;
return 0;
}什么意思呢,就是編譯器會不管int,char這種基本類型,而會去管自定義類型

這是輸出的結(jié)果

到此這篇關(guān)于C++淺析構(gòu)造函數(shù)的特性的文章就介紹到這了,更多相關(guān)C++構(gòu)造函數(shù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C++實現(xiàn)簡單的學(xué)生成績管理系統(tǒng)
這篇文章主要為大家詳細介紹了C++實現(xiàn)簡單的學(xué)生成績管理系統(tǒng),文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-03-03

