C++构造函数初始化列表 委托构造函数

本文介绍C++中构造函数初始化列表的概念及其与普通赋值的区别,特别强调了其在初始化const成员变量的重要性。此外,还展示了如何利用C++11的委托构造函数特性来减少代码重复。

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

(一)构造函数允许使用构造函数初始值列表,来为变量初始化  适用于成员变量有构造函数的任何情况

代码示例:

#include<iostream>
using namespace std;

class Date 
{
public:
     //构造函数初始化列表
     Date(int y, int m, int d) :_year(y), _month(m), _day(d){}
     //默认1970年1月1日  委托构造函数
     Date() :Date(1970, 1, 1){}
     //只给年初始化 月、日都为1  委托构造函数
     Date(int y) :Date(y,1,1){}
     //拷贝构造函数
     Date(const Date & d) :_year(d._year),_month(d._month),_day(d._day){}
     void Display()
     {
          cout << _year << "年" << _month << "月" << _day << "日" << endl;
     }
     ~Date()
     {
          cout << "析构函数!" << endl;
     }
     /*bool operator==(const Date& d)
     {
          return this->_year == d._year&&this->_month == d._month&&this->_day == d._day;
     }*/
     friend bool operator==(const Date &d1, const Date &d2);
    
private:
     int _year;
     int _month;
     int
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值