網站首頁 編程語言 正文
構造函數的概念
構造函數是一個特殊的成員函數,名字與類名相同,創建類類型對象時由編譯器自動調用,保證每個數據成員都有一個合適的初始值,并且在對象的生命周期內只調用一次。
構造函數的特性
(1)函數名與類名相同。
(2)無返回值。
(3)編譯器自動調用對應的構造函數。
(4)構造函數可以重載。
我們這里直接舉一個例子
#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;
}
于是得到的的結果為:
只能有一個構造函數
無參的構造函數和全缺省的構造函數都稱為默認構造函數,并且默認構造函數只能有一個。
下面舉一個錯誤案例:
#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;
}
上面的代碼中,有兩個默認的構造函數,因為不帶參數的構造函數和全缺省的構造函數都被看為默認的構造函數,所以說,現在有兩個構造函數,編譯器不知道到底要去調用哪個構造函數,所以說,就會報錯,所以我們刪除一個就可以了。
關于編譯器生成的默認成員函數,很多人會有疑惑:在我們不實現構造函數的情況下,編譯器會生成默認的構造函數。但是看起來默認構造函數又沒什么用?對象調用了編譯器生成的默認構造函數,但是對象year/month/_day,依舊是隨機值。也就說在這里編譯器生成的默認構造函數并沒有什么用?
解答:C++把類型分成內置類型(基本類型)和自定義類型。內置類型就是語法已經定義好的類型:如int/char...,自定義類型就是我們使用class/struct/union自己定義的類型,看看下面的程序,就發發現編譯器生成默認的構造函數會對自定類型成員_t調用的它的默認成員函數
class Time
{
public:
Time()
{
cout << "Time()" << endl;
_hour = 0;
_minute = 0;
_second = 0;
}
private:
int _hour;
int _minute;
int _second;
};
class Date
{
private:
// 基本類型(內置類型)
int _year;
int _month;
int _day;
// 自定義類型
Time _t;
};
int main()
{
Date d;
return 0;
}
什么意思呢,就是編譯器會不管int,char這種基本類型,而會去管自定義類型
這是輸出的結果
原文鏈接:https://blog.csdn.net/qq_62718027/article/details/124899849
相關推薦
- 2022-04-06 .Net使用加密升級數據安全_實用技巧
- 2023-06-13 react實現組件狀態緩存的示例代碼_React
- 2022-06-02 Go語言數據類型詳細介紹_Golang
- 2023-12-11 Mybatis數據庫操作筆記(Mybatis基礎CRUD代碼)
- 2022-07-01 Oracle的約束介紹與約束維護_oracle
- 2022-11-19 詳解C語言內核中的鏈表與結構體_C 語言
- 2022-04-12 【debug】error: no matching function for call to ‘ma
- 2022-09-19 golang圖片處理庫image基本操作_Golang
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支