網(wǎng)站首頁 編程語言 正文
一.const修飾類的成員函數(shù)
1.問題引出:
給出一段簡單的代碼
代碼段:
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
class Date1
{
public:
Date1(int year = 2000) 類的全缺省構(gòu)造函數(shù)(可無參調(diào)用)
{
_year = year;
}
void Prin()
{
cout << "Print Date:" << _year << endl;
}
private:
int _year;
};
int main()
{
const Date1 a; 定義一個(gè)const修飾的對象a(該對象只可讀,不可被寫入)
a.Prin();
return 0;
}
該段程序會(huì)編譯報(bào)錯(cuò):
2.問題分析
上述代碼段出錯(cuò)的原因要從類的成員函數(shù)的隱含參數(shù)this指針出發(fā)進(jìn)行分析:
注意:
- 由于a是const修飾的對象,因此&a 取出的是 const Date *類型的指針,該指針只可對a對象的內(nèi)存空間進(jìn)行讀取操作而不可進(jìn)行寫入操作(該指針的權(quán)限為只可讀取不可寫入)。
- Prin函數(shù)的形參是Date * const this指針,該類型指針同時(shí)具有讀取和寫入內(nèi)存空間的權(quán)限。
- 將&a賦給Prin的形參this,就會(huì)使指針的讀寫權(quán)限被放大,因此編譯無法通過(指針是靈活而危險(xiǎn)的存在,編譯器只允許其讀寫權(quán)限被縮小而不允許其權(quán)限被放大)
3.const修飾類的成員函數(shù)?
我們知道類的每個(gè)成員函數(shù)都有一個(gè)隱含的this指針形參(類型為:類名*const this)。
為了使被const修飾的對象(比如是上面代碼段中的a)可以調(diào)用其成員對象,C++規(guī)定可以用const來修飾類的成員函數(shù)。
類中被const修飾的“成員函數(shù)”稱為const成員函數(shù),const修飾類成員函數(shù),本質(zhì)上修飾該成員函數(shù)隱含的this指針,表明在該成員函數(shù)中不能對類的任何成員變量進(jìn)行修改。(修飾后成員函數(shù)的this指針形參類型變?yōu)椋?u>const 類名* const this)
比如:
const修飾的對象不可以調(diào)用非const修飾的成員函數(shù)(類指針傳參給this指針時(shí)讀寫權(quán)限被放大):
非const修飾的對象可以調(diào)用const修飾的成員函數(shù)(類指針傳參給this指針時(shí)讀寫權(quán)限被縮小):
const修飾的成員函數(shù)內(nèi)不可以調(diào)用其它的非const修飾的成員函數(shù)(this指針之間傳參時(shí)讀寫權(quán)限被放大):
非const修飾的成員函數(shù)內(nèi)可以調(diào)用其它的const修飾的成員函數(shù)(this指針之間傳參時(shí)讀寫權(quán)限被縮小):
當(dāng)類的成員函數(shù)中沒有對類的成員變量進(jìn)行任何形式的修改操作時(shí),該成員函數(shù)最好都用const來修飾(這樣安全同時(shí)又使得const修飾的對象可以調(diào)用該成員函數(shù))以保證代碼的健壯性。
二. 類的兩個(gè)默認(rèn)的&運(yùn)算符重載
編譯器會(huì)默認(rèn)生成兩個(gè)類的&(取地址)重載用于類的取地址操作(如果我們自定義了類的取地址重載則編譯器便不會(huì)再生成默認(rèn)的)
C++中,內(nèi)置運(yùn)算符若要直接作用于類對象則必須經(jīng)過重載。
若想取到類對象的地址,我們可以對&運(yùn)算符進(jìn)行重載,比如:
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
class Date1
{
public:
Date1(int year = 2000)
{
_year = year;
}
Date1* operator& () 對&進(jìn)行重載用于非const修飾的對象的取地址
{
return this;
}
const Date1* operator&() const 對&進(jìn)行重載用于const修飾的對象的取地址
{
return this;
}
private:
int _year;
};
int main()
{
const Date1 a; 定義一個(gè)const修飾的對象a(該對象只可讀,不可被寫入)
Date1 b;
cout << &a << endl;
cout << &b << endl;
return 0;
}
這兩個(gè)默認(rèn)成員函數(shù)一般不用重新自定義 ,編譯器默認(rèn)會(huì)生成,編譯其默認(rèn)生成的&重載和上面我們自定義的成員函數(shù)應(yīng)該沒有什么區(qū)別(至少功能上沒區(qū)別)。
三. 日期類小練習(xí)?
日期類頭文件:
為了提高代碼的可維護(hù)性和可讀性,將日期類的成員函數(shù)的聲明和定義分開寫。
#pragma once
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
//記錄日期的類
class Date
{
public:
//Date的構(gòu)造函數(shù)
Date(int day=1, int month=1, int year=1);
//獲取月份天數(shù)的方法
int GetMonthday(const int month) const;
//類對象的日期打印函數(shù)
void Print() const;
//判斷某個(gè)日期是星期幾,并打印出來
void GetWeekDay() const ;
//一組比較運(yùn)算符的重載
bool operator> (const Date& date)const;
bool operator==(const Date& date)const;
//在邏輯上我們只需定義出大于(或小于)和等于的判斷函數(shù),剩余的判斷函數(shù)我們就可以通過復(fù)用的方
式簡化代碼書寫
bool operator<(const Date& date)const;
bool operator>=(const Date& date)const;
bool operator<=(const Date& date)const;
bool operator!=(const Date& date)const;
//一組日期+(-)整數(shù)的操作和+=(-=)整數(shù)的操作
Date operator+(const int day)const;
Date& operator+=(const int day);
Date operator-(const int day)const;
Date& operator-=(const int day);
Date& operator=(const Date& date);
//一組前置++(--)和后置++(--)的重載
Date& operator++(); //實(shí)現(xiàn)日期類的前置++
Date operator++(int); //實(shí)現(xiàn)日期類的后置++
Date& operator--(); //實(shí)現(xiàn)日期類的前置--
Date operator--(int); //實(shí)現(xiàn)日期類的后置--
//實(shí)現(xiàn)時(shí)期相減的操作符重載
int operator-(const Date& date)const;
private:
int _day;
int _month;
int _year;
};
日期類的成員函數(shù)的實(shí)現(xiàn):
#include "Date.h"
//Date的構(gòu)造函數(shù)
Date ::Date(int day, int month, int year)
{
_day = day;
_month = month;
_year = year;
if (_year <= 0 || _month <= 0 || _month > 12 || _day <= 0 || _day > GetMonthday(_month))
{
cout << "date invalued please exit the app" << endl;
exit(0);
}
}
//獲取相應(yīng)月份天數(shù)的方法
int Date::GetMonthday(const int month)const
{
static const int arr[12] = { 31,28,31,30,31,30,31,31,30,31,30,31 };
int ret = arr[month - 1];
if (((0 == _year % 4 && 0 != _year % 100) || (0 == _year % 400)) && 2 == month)
{
ret++;
}
return ret;
}
//類對象的日期打印函數(shù)
void Date::Print()const
{
cout << _year << ' ' << _month << ' ' << _day << ' ' << endl;
}
//判斷某個(gè)日期是星期幾,并打印出來
//注意this指針不能由用戶去傳
void Date::GetWeekDay()const
{
const char* arr[7] = { "星期一","星期二","星期三","星期四","星期五","星期六","星期日" };
const Date tem(1, 1, 1900);
const int subret = (*this)-tem;
printf("%s\n", arr[(subret % 7)]);
}
//將 > 運(yùn)算符進(jìn)行重載
bool Date ::operator> (const Date& date)const
{
if (_year > date._year)
{
return true;
}
else if (_year == date._year && _month > date._month)
{
return true;
}
else if (_year == date._year && _month == date._month && _day > date._day)
{
return true;
}
return false;
}
//將 =運(yùn)算符進(jìn)行重載
bool Date:: operator==(const Date& date)const
{
if (date._day == _day && date._month == _month && date._year == _year)
{
return true;
}
return false;
}
//在邏輯上我們只需定義出大于(或小于)和等于的判斷函數(shù),剩余的判斷函數(shù)我們就可以通過復(fù)用的方式簡化代碼書寫
bool Date :: operator>= (const Date& date)const
{
if ((*this) > date || (*this) == date)
{
return true;
}
return false;
}
bool Date :: operator < (const Date& date)const
{
if ((*this) >= date)
{
return false;
}
return true;
}
bool Date :: operator<=(const Date& date)const
{
if ((*this) > date)
{
return false;
}
return true;
}
bool Date:: operator!= (const Date& date)const
{
if ((*this) == date)
{
return false;
}
return true;
}
//一組日期+(-)整數(shù)的操作和+=(-=)整數(shù)的操作
Date& Date::operator+=(const int day)
{
if (day < 0)
{
(*this) -= (-day);
return (*this);
}
_day += day;
while (_day > GetMonthday(_month))
{
if (_month < 12)
{
_day -= GetMonthday(_month);
_month++;
}
else
{
_day -= GetMonthday(_month);
_year++;
_month = 1;
}
}
return (*this);
}
Date Date::operator+(const int day)const
{
Date tem(*this);
tem += day;
return tem;
}
Date& Date::operator-=(const int day)
{
if (day < 0)
{
(*this) += (-day);
return (*this);
}
_day -= day;
while (_day <= 0 )
{
if (_month > 1)
{
_month--;
_day += GetMonthday(_month);
}
else
{
_year--;
_month = 12;
_day += GetMonthday(_month);
}
}
if (_year <= 0)
{
cout << "operation invalued" << endl;
exit(0);
}
return (*this);
}
Date Date::operator-(int day)const
{
Date tem(*this);
tem -= (day);
return tem;
}
Date& Date ::operator=(const Date& date)
{
if (this != &date)
{
_day = date._day;
_month = date._month;
_year = date._year;
}
return (*this);
}
//一組前置++(--)和后置++(--)的重載
Date& Date ::operator++() //實(shí)現(xiàn)日期類的前置++
{
(*this) += 1;
return (*this);
}
Date Date ::operator++(int) //實(shí)現(xiàn)日期類的后置++
{
Date tem(*this);
(*this) += 1;
return tem;
}
Date& Date:: operator--() //實(shí)現(xiàn)日期類的前置--
{
(*this) -= 1;
return (*this);
}
Date Date:: operator--(int) //實(shí)現(xiàn)日期類的后置--
{
Date tem(*this);
(*this) -= 1;
return tem;
}
//實(shí)現(xiàn)時(shí)期相減的操作符重載
int Date::operator-(const Date& date)const
{
int count = 0;
Date min;
if ((*this) < date)
{
min = (*this);
while (min != date)
{
min++;
count++;
}
return -count;
}
else
{
min = date;
while (min != (*this))
{
min++;
count++;
}
return count;
}
}
總結(jié)
原文鏈接:https://blog.csdn.net/weixin_73470348/article/details/128761564
相關(guān)推薦
- 2022-08-02 python3線程池ThreadPoolExecutor處理csv文件數(shù)據(jù)_python
- 2022-02-18 ImportError:can't import name 'Flask'
- 2023-07-02 python中編寫config文件并及時(shí)更新的方法_python
- 2022-05-20 Spring-IOC—基于注解配置Bean
- 2022-07-08 python中的type,元類,類,對象用法_python
- 2022-10-06 C#?獲取本機(jī)IP地址(IPv4和IPv6)_C#教程
- 2023-01-13 pytorch如何定義新的自動(dòng)求導(dǎo)函數(shù)_python
- 2023-03-26 Android視圖綁定方法深入探究_Android
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運(yùn)行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲(chǔ)小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運(yùn)算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯(cuò)誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實(shí)現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡單動(dòng)態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊(duì)列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支