C++:类中const修饰的成员函数

简介: C++:类中const修饰的成员函数

目录

一.const修饰类的成员函数

1.问题引出:

代码段:

2.问题分析

3.const修饰类的成员函数

二. 类的两个默认的&运算符重载

三. 日期类小练习

一.const修饰类的成员函数
1.问题引出:
给出一段简单的代码

代码段:

include

using std::cin;
using std::cout;
using std::endl;

class Date1
{
public:

Date1(int year = 2000)             类的全缺省构造函数(可无参调用)
{
    _year = year;
}

void Prin()
{
    cout << "Print Date:" << _year << endl;
}

private:

int _year;

};

int main()
{

const Date1 a;                       定义一个const修饰的对象a(该对象只可读,不可被写入)
a.Prin();

return 0;

}

该段程序会编译报错:

2.问题分析
上述代码段出错的原因要从类的成员函数的隐含参数this指针出发进行分析:

注意:

由于a是const修饰的对象,因此&a 取出的是 const Date *类型的指针,该指针只可对a对象的内存空间进行读取操作而不可进行写入操作(该指针的权限为只可读取不可写入)。
Prin函数的形参是Date * const this指针,该类型指针同时具有读取和写入内存空间的权限。
将&a赋给Prin的形参this,就会使指针的读写权限被放大,因此编译无法通过(指针是灵活而危险的存在,编译器只允许其读写权限被缩小而不允许其权限被放大)
3.const修饰类的成员函数
我们知道类的每个成员函数都有一个隐含的this指针形参(类型为:类名*const this)。

为了使被const修饰的对象(比如是上面代码段中的a)可以调用其成员对象,C++规定可以用const来修饰类的成员函数。

类中被const修饰的“成员函数”称为const成员函数,const修饰类成员函数,本质上修饰该成员函数隐含的this指针,表明在该成员函数中不能对类的任何成员变量进行修改。(修饰后成员函数的this指针形参类型变为:const 类名* const this)
比如:

const修饰的对象不可以调用非const修饰的成员函数(类指针传参给this指针时读写权限被放大):
非const修饰的对象可以调用const修饰的成员函数(类指针传参给this指针时读写权限被缩小):
const修饰的成员函数内不可以调用其它的非const修饰的成员函数(this指针之间传参时读写权限被放大):
非const修饰的成员函数内可以调用其它的const修饰的成员函数(this指针之间传参时读写权限被缩小):
当类的成员函数中没有对类的成员变量进行任何形式的修改操作时,该成员函数最好都用const来修饰(这样安全同时又使得const修饰的对象可以调用该成员函数)以保证代码的健壮性。
二. 类的两个默认的&运算符重载

编译器会默认生成两个类的&(取地址)重载用于类的取地址操作(如果我们自定义了类的取地址重载则编译器便不会再生成默认的)
C++中,内置运算符若要直接作用于类对象则必须经过重载。

若想取到类对象的地址,我们可以对&运算符进行重载,比如:

include

using std::cin;
using std::cout;
using std::endl;

class Date1
{
public:

Date1(int year = 2000)
{
    _year = year;
}


Date1* operator& ()               对&进行重载用于非const修饰的对象的取地址
{
    return this;
}

const Date1* operator&() const    对&进行重载用于const修饰的对象的取地址
{
    return this;
}

private:

int _year;

};

int main()
{

const Date1 a;                     定义一个const修饰的对象a(该对象只可读,不可被写入)
Date1 b;

cout << &a << endl;
cout << &b << endl;

return 0;

}

这两个默认成员函数一般不用重新自定义 ,编译器默认会生成,编译其默认生成的&重载和上面我们自定义的成员函数应该没有什么区别(至少功能上没区别)。

三. 日期类小练习
日期类头文件:

为了提高代码的可维护性和可读性,将日期类的成员函数的声明和定义分开写。

pragma once

include

using std::cout;
using std::cin;
using std::endl;

//记录日期的类
class Date
{
public:

//Date的构造函数
Date(int day=1, int month=1, int year=1);        
//获取月份天数的方法
int GetMonthday(const int month) const;
//类对象的日期打印函数
void Print() const;
//判断某个日期是星期几,并打印出来
void GetWeekDay() const ;






//一组比较运算符的重载
bool operator> (const Date& date)const;                
bool operator==(const Date& date)const;
//在逻辑上我们只需定义出大于(或小于)和等于的判断函数,剩余的判断函数我们就可以通过复用的方    
式简化代码书写
bool operator<(const Date& date)const;
bool operator>=(const Date& date)const;
bool operator<=(const Date& date)const;
bool operator!=(const Date& date)const;




//一组日期+(-)整数的操作和+=(-=)整数的操作
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++();                                 //实现日期类的前置++
Date operator++(int);                             //实现日期类的后置++
Date& operator--();                              //实现日期类的前置--
Date operator--(int);                            //实现日期类的后置--





//实现时期相减的操作符重载
int operator-(const Date& date)const;



private:

int _day;
int _month;
int _year;

};

日期类的成员函数的实现:

include "Date.h"

//Date的构造函数
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);
}

}
//获取相应月份天数的方法
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;

}
//类对象的日期打印函数
void Date::Print()const
{

cout << _year << ' ' << _month << ' ' << _day << ' ' << endl;

}
//判断某个日期是星期几,并打印出来
//注意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)]);

}

//将 > 运算符进行重载
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;

}
//将 =运算符进行重载
bool Date:: operator==(const Date& date)const
{

if (date._day == _day && date._month == _month && date._year == _year)
{
    return true;
}
return false;

}
//在逻辑上我们只需定义出大于(或小于)和等于的判断函数,剩余的判断函数我们就可以通过复用的方式简化代码书写
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;

}

//一组日期+(-)整数的操作和+=(-=)整数的操作
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++() //实现日期类的前置++
{

(*this) += 1;
return (*this);

}
Date Date ::operator++(int) //实现日期类的后置++
{

Date tem(*this);
(*this) += 1;
return tem;

}
Date& Date:: operator--() //实现日期类的前置--
{

(*this) -= 1;
return (*this);

}
Date Date:: operator--(int) //实现日期类的后置--
{

Date tem(*this);
(*this) -= 1;
return tem;

}

//实现时期相减的操作符重载
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;
}

}

相关文章
|
6月前
|
人工智能 机器人 编译器
c++模板初阶----函数模板与类模板
class 类模板名private://类内成员声明class Apublic:A(T val):a(val){}private:T a;return 0;运行结果:注意:类模板中的成员函数若是放在类外定义时,需要加模板参数列表。return 0;
191 0
|
6月前
|
存储 编译器 程序员
c++的类(附含explicit关键字,友元,内部类)
本文介绍了C++中类的核心概念与用法,涵盖封装、继承、多态三大特性。重点讲解了类的定义(`class`与`struct`)、访问限定符(`private`、`public`、`protected`)、类的作用域及成员函数的声明与定义分离。同时深入探讨了类的大小计算、`this`指针、默认成员函数(构造函数、析构函数、拷贝构造、赋值重载)以及运算符重载等内容。 文章还详细分析了`explicit`关键字的作用、静态成员(变量与函数)、友元(友元函数与友元类)的概念及其使用场景,并简要介绍了内部类的特性。
281 0
|
8月前
|
编译器 C++ 容器
【c++11】c++11新特性(上)(列表初始化、右值引用和移动语义、类的新默认成员函数、lambda表达式)
C++11为C++带来了革命性变化,引入了列表初始化、右值引用、移动语义、类的新默认成员函数和lambda表达式等特性。列表初始化统一了对象初始化方式,initializer_list简化了容器多元素初始化;右值引用和移动语义优化了资源管理,减少拷贝开销;类新增移动构造和移动赋值函数提升性能;lambda表达式提供匿名函数对象,增强代码简洁性和灵活性。这些特性共同推动了现代C++编程的发展,提升了开发效率与程序性能。
325 12
|
9月前
|
编译器 C++
类和对象(下)C++
本内容主要讲解C++中的初始化列表、类型转换、静态成员、友元、内部类、匿名对象及对象拷贝时的编译器优化。初始化列表用于成员变量定义初始化,尤其对引用、const及无默认构造函数的类类型变量至关重要。类型转换中,`explicit`可禁用隐式转换。静态成员属类而非对象,受访问限定符约束。内部类是独立类,可增强封装性。匿名对象生命周期短,常用于临时场景。编译器会优化对象拷贝以提高效率。最后,鼓励大家通过重复练习提升技能!
|
10月前
|
编译器 C++ 开发者
【C++篇】深度解析类与对象(下)
在上一篇博客中,我们学习了C++的基础类与对象概念,包括类的定义、对象的使用和构造函数的作用。在这一篇,我们将深入探讨C++类的一些重要特性,如构造函数的高级用法、类型转换、static成员、友元、内部类、匿名对象,以及对象拷贝优化等。这些内容可以帮助你更好地理解和应用面向对象编程的核心理念,提升代码的健壮性、灵活性和可维护性。
|
9月前
|
设计模式 安全 C++
【C++进阶】特殊类设计 && 单例模式
通过对特殊类设计和单例模式的深入探讨,我们可以更好地设计和实现复杂的C++程序。特殊类设计提高了代码的安全性和可维护性,而单例模式则确保类的唯一实例性和全局访问性。理解并掌握这些高级设计技巧,对于提升C++编程水平至关重要。
189 16
|
10月前
|
编译器 C语言 C++
类和对象的简述(c++篇)
类和对象的简述(c++篇)
|
9月前
|
编译器 C++
类和对象(中 )C++
本文详细讲解了C++中的默认成员函数,包括构造函数、析构函数、拷贝构造函数、赋值运算符重载和取地址运算符重载等内容。重点分析了各函数的特点、使用场景及相互关系,如构造函数的主要任务是初始化对象,而非创建空间;析构函数用于清理资源;拷贝构造与赋值运算符的区别在于前者用于创建新对象,后者用于已存在的对象赋值。同时,文章还探讨了运算符重载的规则及其应用场景,并通过实例加深理解。最后强调,若类中存在资源管理,需显式定义拷贝构造和赋值运算符以避免浅拷贝问题。
|
9月前
|
存储 编译器 C++
类和对象(上)(C++)
本篇内容主要讲解了C++中类的相关知识,包括类的定义、实例化及this指针的作用。详细说明了类的定义格式、成员函数默认为inline、访问限定符(public、protected、private)的使用规则,以及class与struct的区别。同时分析了类实例化的概念,对象大小的计算规则和内存对齐原则。最后介绍了this指针的工作机制,解释了成员函数如何通过隐含的this指针区分不同对象的数据。这些知识点帮助我们更好地理解C++中类的封装性和对象的实现原理。
|
9月前
|
安全 C++
【c++】继承(继承的定义格式、赋值兼容转换、多继承、派生类默认成员函数规则、继承与友元、继承与静态成员)
本文深入探讨了C++中的继承机制,作为面向对象编程(OOP)的核心特性之一。继承通过允许派生类扩展基类的属性和方法,极大促进了代码复用,增强了代码的可维护性和可扩展性。文章详细介绍了继承的基本概念、定义格式、继承方式(public、protected、private)、赋值兼容转换、作用域问题、默认成员函数规则、继承与友元、静态成员、多继承及菱形继承问题,并对比了继承与组合的优缺点。最后总结指出,虽然继承提高了代码灵活性和复用率,但也带来了耦合度高的问题,建议在“has-a”和“is-a”关系同时存在时优先使用组合。
491 6