C++类中const修饰的成员函数及日期类小练习

目录
  • 一.const修饰类的成员函数
    • 1.问题引出:
    • 2.问题分析
    • 3.const修饰类的成员函数
  • 二. 类的两个默认的&运算符重载
  • 三. 日期类小练习
  • 总结

一.const修饰类的成员函数

1.问题引出:

给出一段简单的代码

代码段:

#include <iostream>
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 <iostream>
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 <iostream>
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;
	}
}

总结

到此这篇关于C++类中const修饰的成员函数及日期类小练习的文章就介绍到这了,更多相关C++类const修饰的成员函数内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • C++类成员函数后面加const问题

    目录 C++类成员函数后面加const C++const四种用法 一.用const修饰函数参数 二.用const修饰局部或全局变量 三.用const修饰函数返回值 四.用const修饰函数 C++类成员函数后面加const 如果类的成员函数后面加了const关键字,说明这个函数是不能改变类中的成员变量的. 如果在编写该函数会修改类中的成员变量,编译时会出错,并且也提高了程序的可读性,当我们看到函数后面有const的话就知道这个函数是不会修改类中数据的. 注意: 1.只能加在非静态成员函数后面,加

  • C++ 中const对象与const成员函数的实例详解

    C++ 中const对象与const成员函数的实例详解 const对象只能调用const成员函数: #include<iostream> using namespace std; class A { public: void fun()const { cout<<"const 成员函数!"<<endl; } void fun() { cout<<"非const成员函数 !"<<endl; } }; int

  • C++知识点之成员函数中const的用法

    目录 修饰入参 值传递 址传递 const修饰入参 修饰返回值 修饰函数 const 在C++中是一个很重要的关键字,其不光可以用来修饰变量,还可以放在函数定义中,这里整理了其在函数中的三个用法. 修饰入参 首先我们要明白在C++中调用函数时存在两种方法,即传递值和传递引用. 值传递 值传递时,调用函数时会创建入参的拷贝,函数中的操作不会对原值进行修改,因此这种方式中不需要使用 const 来修饰入参,因为其只是对拷贝的临时对象进行操作. 址传递 传递地址时函数中的操作实际上是直接对原来的值进行

  • C++成员函数中const的使用详解

    目录 修饰入参 值传递 址传递 const修饰入参 修饰返回值 修饰函数 总结 const 在C++中是一个很重要的关键字,其不光可以用来修饰变量,还可以放在函数定义中,这里整理了其在函数中的三个用法. 修饰入参 首先我们要明白在C++中调用函数时存在两种方法,即传递值和传递引用. 值传递 值传递时,调用函数时会创建入参的拷贝,函数中的操作不会对原值进行修改,因此这种方式中不需要使用 const 来修饰入参,因为其只是对拷贝的临时对象进行操作. 址传递 传递地址时函数中的操作实际上是直接对原来的

  • C++类中const修饰的成员函数及日期类小练习

    目录 一.const修饰类的成员函数 1.问题引出: 2.问题分析 3.const修饰类的成员函数 二. 类的两个默认的&运算符重载 三. 日期类小练习 总结 一.const修饰类的成员函数 1.问题引出: 给出一段简单的代码 代码段: #include <iostream> using std::cin; using std::cout; using std::endl; class Date1 { public: Date1(int year = 2000) 类的全缺省构造函数(可

  • C++类中的六大默认成员函数详解

    在C++中,当你去创建一个类的时候,即便这个类是空类,也会自动生成下面6个默认成员函数,在本篇博客中,我将逐一分析下面6个默认成员函数. 构造函数 构造函数并不是去构造函数的函数,而是去对函数进行初始化的函数.构造函数的函数名与类名相同,当我们每次创建类对象的时候,就会自动调用构造函数.构造函数在对象的生命周期中只会调用1次. class Date { public: //构造函数 Date(int year = 2021, int month = 4, int day = 11) { _yea

  • 剖析C++编程中friend关键字所修饰的友元函数和友元类

    在某些情况下,为不是类成员的函数或单独类中的所有函数授予成员级别的访问权会更方便.仅类实现器可以声明其友元.函数或类不能将其自身声明为任何类的友元.在类声明中,使用 friend 关键字和非成员函数名称或其他类,以允许其访问你的类的专用和受保护成员. 语法 friend class-name; friend function-declarator; 友元声明 如果声明以前未声明的友元函数,则该函数将被导出到封闭非类范围. 友元声明中声明的函数被视为已使用 extern 关键字声明.(有关 ext

  • C++ 中const修饰虚函数实例详解

    C++ 中const修饰虚函数实例详解 [1]程序1 #include <iostream> using namespace std; class Base { public: virtual void print() const = 0; }; class Test : public Base { public: void print(); }; void Test::print() { cout << "Test::print()" << end

  • c++ 类中const成员变量的赋值方法

    在头文件的类的定义中定义了一个const成员变量c++ 规则: 1.类定义中不能进行初始化,因为头文件中类的定义只是一个声明,并没有分配真正空间,因此变量是不存在的,因此是不能赋值的. 2.const 定义的变量是不能赋值 这可如何是好,声明中不能赋值,声明完还不能赋值.又不能不赋值. 解决方案: 1.在构造函数后的参数初始化列表中初始化 2.将const变量同时声明为 static 类型进行初始化. Eg: #include <iostream> class CTestA { public:

  • C++中const修饰符的详解及其作用介绍

    目录 概述 常对象 常对象成员 常成员函数 常数据成员 数据成员访问限制 常对象修改的限制 常指针 指向常变量的指针 指向对象的指针 小结 对象的常引用 总结 概述 const 是 constant 的缩写, 是不变的意思. 在 C++ 中是用来修饰内置类型变量, 自定义对象, 成员函数, 返回值, 函数参数. const 可以帮我们避免无意之中的错误操作. 使用 const, 把有关的数据定义为常量 (常变量 / 常对象 / 常函数). const 既可以使数据在一定范围内共享, 又要保证它不

  • C++类中的常数据成员与静态数据成员之间的区别

    刚开始学习C++的类和对象的部分,对类中的常数据成员和静态数据成员的概念和用法经常混淆,所以今天整理一下,顺便说一下,今天是我的生日,祝我生日快乐,呵呵. 常数据成员常数据成员是指在类中定义的不能修改其值的一些数据成员,类似于我们以前学过的常变量,虽然是变量,也有自己的地址,但是一经赋初值,便不能再被修改. 适用于类中定义一些初始化之后不希望被修改的变量. 定义方法: 复制代码 代码如下: const 类型名 变量名; (1)类中的常数据成员只能通过构造函数的参数初始化表进行初始化. (2)常数

  • 详谈Java中Object类中的方法以及finalize函数作用

    Object是所有类的父类,任何类都默认继承Object. 一.Object类中的方法 1.clone方法 保护方法,实现对象的浅复制,只有实现了Cloneable接口才可以调用该方法,否则抛出CloneNotSupportedException异常. 主要是JAVA里除了8种基本类型传参数是值传递,其他的类对象传参数都是引用传递,我们有时候不希望在方法里讲参数改变,这是就需要在类中复写clone方法. 2.getClass方法 final方法,获得运行时类型. 3.toString方法 该方法

  • js对象内部访问this修饰的成员函数示例

    用wrapper封装这样在对象内外都可以访问 复制代码 代码如下: function MapPool(){ function createMarker(name, lat, lng, state){  var marker = new AMap.Marker({   position : new AMap.LngLat(lng, lat),        });  //the function mapMoveTo is not accessible here too        AMap.ev

  • C#类中的属性使用总结(详解类的属性)

    复制代码 代码如下: private int dd;  public int dd  {      get{ return xx*3;}      set{ xx = value/3;}  } 没有set的属性是一种只读属性,没有get的访问器是一种只写属性.(1) get访问器用来返回字段或者计算 并返回字段,它必须以return或者throw终结. 复制代码 代码如下: private string name;  public string Name  {      get      { 

随机推荐