1.日期类的完整实现
//Date.h
#pragma once
#include<iostream>
#include <assert.h>
using namespace std;
// 一个到底可以重载哪些运算符?-》哪些运算符对这个类型有意义
class Date
{
// 友元函数 -- 这个函数内部可以使用Date对象访问私有保护成员
friend ostream& operator<<(ostream& out, const Date& d);
friend istream& operator>>(istream& in, Date& d);
public:
// 获取某年某月的天数
// 会频繁调用,所以直接放在类里面定义作为inline
int GetMonthDay(int year, int month)
{
static int days[13] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
int day = days[month];
if (month == 2
&& ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)))
{
day += 1;
}
return day;
}
bool CheckDate()
{
if (_year >= 1
&& _month > 0 && _month < 13
&& _day > 0 && _day <= GetMonthDay(_year, _month))
{
return true;
}
else
{
return false;
}
}
// 构造会频繁调用,所以直接放在类里面定义作为inline
Date(int year = 1, int month = 1, int day = 1)
{
_year = year;
_month = month;
_day = day;
/*if (!CheckDate())
{
Print();
cout << "刚构造的日期非法" << endl;
}*/
assert(CheckDate());
}
void Print() const;
bool operator==(const Date& d) const;
bool operator!=(const Date& d) const;
bool operator>(const Date& d) const;
bool operator>=(const Date& d) const;
bool operator<(const Date& d) const;
bool operator<=(const Date& d) const;
Date operator+(int day) const;
Date& operator+=(int day);
// ++d1;
// d1++;
// 直接按特性重载,无法区分
// 特殊处理,使用重载区分,后置++重载增加一个int参数跟前置构成函数重载进行区分
Date& operator++(); // 前置
Date operator++(int); // 后置
// d1 - 100
Date operator-(int day) const;
Date& operator-=(int day);
Date& operator--(); // 前置
Date operator--(int); // 后置
// d1 - d2
int operator-(const Date& d) const;
//void operator<<(ostream& out);
private:
int _year;
int _month;
int _day;
};
// 流插入重载
inline ostream& operator<<(ostream& out, const Date& d)
{
out << d._year << "年" << d._month << "月" << d._day << "日" << endl;
return out;
}
// 流提取重载
inline istream& operator>>(istream& in, Date& d)
{
in >> d._year >> d._month >> d._day;
assert(d.CheckDate());
return in;
}
//Date.cpp
#include "Date.h"
// const int* const ptr;
// void Date::Print(const Date* const this)
void Date::Print() const
{
//_year = 1;
cout << _year << "/" << _month << "/" << _day << endl;
}
// 任何一个类,只需要写一个> == 或者 < ==重载 剩下比较运算符重载复用即可
bool Date::operator== (const Date& d) const
{
return _year == d._year
&& _month == d._month
&& _day == d._day;
}
// d1 != d2
bool Date::operator!=(const Date& d) const
{
return !(*this == d);
}
// d1 > d2
bool Date::operator>(const Date& d) const
{
if ((_year > d._year)
|| (_year == d._year && _month > d._month)
|| (_year == d._year && _month == d._month && _day > d._day))
{
return true;
}
else
{
return false;
}
}
bool Date::operator>=(const Date& d) const
{
return (*this > d) || (*this == d);
}
bool Date::operator<(const Date& d) const
{
return !(*this >= d);
}
bool Date::operator<=(const Date& d) const
{
return !(*this > d);
}
// d1 + 100
Date Date::operator+(int day) const
{
//Date ret(*this);
Date ret = *this;
ret += day;
return ret;
}
// d2 += d1 += 100
Date& Date::operator+=(int day)
{
if (day < 0)
{
return *this -= -day;
}
_day += day;
while (_day > GetMonthDay(_year, _month))
{
_day -= GetMonthDay(_year, _month);
++_month;
if (_month == 13)
{
_year++;
_month = 1;
}
}
return *this;
}
//Date Date::operator+(int day)
//{
// Date ret = *this;
// // ...
// ret._day += day;
// while (ret._day > GetMonthDay(ret._year, ret._month))
// {
// //...
// }
//
// return ret;
//}
//
d1 += 100
//Date& Date::operator+=(int day)
//{
// *this = *this + day;
//
// return *this;
//}
Date& Date::operator++() // 前置
{
//*this += 1;
//return *this;
return *this += 1;
}
Date Date::operator++(int) // 后置
{
Date tmp(*this);
*this += 1;
return tmp;
}
Date Date::operator-(int day) const
{
Date ret = *this;
ret -= day;
return ret;
}
Date& Date::operator-=(int day)
{
if (day < 0)
{
return *this += -day;
}
_day -= day;
while (_day <= 0)
{
--_month;
if (_month == 0)
{
--_year;
_month = 12;
}
_day += GetMonthDay(_year, _month);
}
return *this;
}
Date& Date::operator--() // 前置
{
return *this -= 1;
}
Date Date::operator--(int) // 后置
{
Date tmp(*this);
*this -= 1;
return tmp;
}
// d1 - d2
int Date::operator-(const Date& d) const
{
int flag = 1;
Date max = *this;
Date min = d;
if (*this < d)
{
max = d;
min = *this;
flag = -1;
}
int n = 0;
while (min != max)
{
++min;
++n;
}
return n * flag;
}
//void Date::operator<<(ostream& out)
//{
// out << _year << "-" << _month << "-" << _day << endl;
//}
//Test.cpp
#include "Date.h"
//class A
//{
//public:
// A(int a = 0)
// {
// _a = a;
// cout << "A(int a = 0)->" <<_a<< endl;
// }
//
// ~A()
// {
// cout << "~A()->" <<_a<<endl;
// }
//private:
// int _a;
//};
//
//A aa3(3);
//
//void f()
//{
// static int i = 0;
// static A aa0(0);
// A aa1(1);
// A aa2(2);
// static A aa4(4);
//}
//
构造顺序:3 0 1 2 4 1 2
析构顺序:~2 ~1 ~2 ~1 ~4 ~0 ~3
//int main()
//{
// f();
// f();
//
// return 0;
//}
//class A
//{
//public:
// A(int a = 0)
// {
// _a = a;
// cout << "A(int a = 0)->" << _a << endl;
// }
//
// // A aa2(aa1);
// A(const A& aa)
// {
// _a = aa._a;
// cout << "A(const A& aa)->" << _a << endl;
// }
//
// ~A()
// {
// cout << "~A()->" << _a << endl;
// }
//private:
// int _a;
//};
//
//void func1(A aa)
//{
//
//}
//
//void func2(A& aa)
//{
//
//}
//
//A func3()
//{
// static A aa(3);
// return aa;
//}
//
//A& func4()
//{
// static A aa(4);
// return aa;
//}
//
//int main()
//{
// //A aa1(1);
// //A aa2(aa1);
//
// //func1(aa1);
// //func2(aa1);
// func3();
// cout << endl << endl;
// func4();
//
// //int i = 0;
// //int& j = i;
// //cout << typeid(j).name() << endl;
//
// return 0;
//}
//#pragma once
//
//class Time
//{
//public:
// Time()
// {
// _hour = 1;
// _minute = 1;
// _second = 1;
// }
//
// Time& operator=(const Time& t)
// {
// cout << "Time& operator=(const Time& t)" << endl;
// if (this != &t)
// {
// _hour = t._hour;
// _minute = t._minute;
// _second = t._second;
// }
//
// return *this;
// }
//private:
// int _hour;
// int _minute;
// int _second;
//};
//
//class Date
//{
//public:
// // 构造会频繁调用,所以直接放在类里面定义作为inline
// Date(int year = 1, int month = 1, int day = 1)
// {
// _year = year;
// _month = month;
// _day = day;
// }
//
// Date(const Date& d)
// {
// cout << "Date(const Date& d)" << endl;
// _year = d._year;
// _month = d._month;
// _day = d._day;
// }
//
// // d1 = d3;
// // d2 = d2;
// //Date& operator=(const Date& d)
// Date operator=(const Date d)
// //{
// // if (this != &d)
// // {
// // _year = d._year;
// // _month = d._month;
// // _day = d._day;
// // }
//
// // return *this;
// //}
//
//private:
// int _year;
// int _month;
// int _day;
//
// // 自定义类型
// Time _t;
//};
//
//
这里会发现下面的程序会崩溃掉?这里就需要我们以后讲的深拷贝去解决。
//typedef int DataType;
//class Stack
//{
//public:
// Stack(size_t capacity = 10)
// {
// _array = (DataType*)malloc(capacity * sizeof(DataType));
// if (nullptr == _array)
// {
// perror("malloc申请空间失败");
// return;
// }
//
// _size = 0;
// _capacity = capacity;
// }
//
// void Push(const DataType& data)
// {
// // CheckCapacity();
// _array[_size] = data;
// _size++;
// }
//
// ~Stack()
// {
// if (_array)
// {
// free(_array);
// _array = nullptr;
// _capacity = 0;
// _size = 0;
// }
// }
//
//private:
// DataType *_array;
// size_t _size;
// size_t _capacity;
//};
//
躺赢 -- 构造、拷贝构造、赋值重载、析构默认生成都可以用
//class MyQueue
//{
//private:
// Stack _st1;
// Stack _st2;
//};
//
//void Test()
//{
// Date d1(2022, 7, 24);
// Date d2(d1);
//
// Date d3(2022, 8, 24);
// d2 = d1 = d3; // d1.operator=(&d1, d3)
// d2 = d2;
//
// Stack st1;
// Stack st2;
// st2.Push(1);
// st2.Push(2);
// st1 = st2; // 实现深拷贝赋值解决
//
// int i = 0, j = 1, k = 2;
// k = i = j = 10;
//}
void TestDate1()
{
Date d1(2022, 7, 24);
Date d2(2022, 7, 25);
Date d3(2021, 7, 25);
cout << (d1 < d2) << endl;
cout << (d1 < d3) << endl;
cout << (d1 == d3) << endl;
cout << (d1 > d3) << endl;
}
void TestDate2()
{
//Date d1(2022, 7, 24);
//d1 += 4;
//d1.Print();
//d1 += 40; // 跨月
//d1.Print();
//d1 += 400;// 跨年
//d1.Print();
//d1 += 4000; // 跨闰年
//d1.Print();
Date d1(2022, 7, 24);
/*Date d2 = d1 + 4;
d2.Print();*/
(d1 + 4).Print();
(d1 + 40).Print();// 跨月
(d1 + 400).Print();// 跨年
(d1 + 4000).Print(); // 跨闰年
(d1 + 40000).Print();
Date ret1 = ++d1; // d1.operator++(&d1)
Date ret2 = d1++; // d1.operator++(&d2, 0)
}
void TestDate3()
{
Date d1(2022, 7, 25);
(d1 - 4).Print();
(d1 - 40).Print();// 跨月
(d1 - 400).Print();// 跨年
(d1 - 4000).Print(); // 跨闰年
(d1 - 40000).Print();
Date d2(2022, 7, 25);
Date d3(2023, 2, 15);
cout << d2 - d3 << endl;
cout << d3 - d2 << endl;
Date d4(2000, 2, 15);
cout << d2 - d4 << endl;
cout << d4 - d2 << endl;
}
void TestDate4()
{
/*Date d1(2022, 7, 32);
d1.Print();
Date d2(2022, 2, 29);
d2.Print();
d2++;
d2.Print();*/
Date d1(2022, 7, 25);
Date d2(2022, 7, 26);
cout << d1 << d2;
cin >> d1 >> d2;
cout << d1 << d2;
//d1.operator<<(cout);
//d1 << cout;
//cout << (d1 + 100);
//(d1 + 100).Print();
//(d1 + -100).Print();
}
void TestDate5()
{
const char* WeeDayToStr[] = { "周一", "周二", "周三", "周四", "周五", "周六", "周天" };
Date d1, d2;
int day = 0;
int option = 0;
do {
cout << "*******************************" << endl;
cout << " 1、日期加/减天数 2、日期减日期" << endl;
cout << " 3、日期->周几 -1、退出" << endl;
cout << "*******************************" << endl;
cout << "请选择:>";
cin >> option;
if (option == 1)
{
cout << "请依次输入日期及天数(减天数就输入负数):";
cin >> d1 >> day;
cout << "日期加减天数后的日期:" << d1 + day << endl;
}
else if (option == 2)
{
cout << "请依次输入两个日期:";
cin >> d1 >> d2;
cout << "相差的天数:" << d1 - d2 << endl;
}
else if (option == 3)
{
cout << "请输入日期:";
cin >> d1;
Date start(1, 1, 1);
int n = d1 - start;
int weekDay = 0; // 周一
weekDay += n;
//weekDay += 9;
//cout << "周" << weekDay % 7 + 1 << endl;
cout << WeeDayToStr[weekDay % 7] << endl;
}
else
{
cout << "无此选项,请重新选择" << endl;
}
} while (option != -1);
}
void TestDate6()
{
Date d1(2022, 7, 25);
const Date d2(2022, 7, 25);
d1.Print();
d2.Print();
d1 < d2;
d2 < d1;
}
//int main()
//{
// //TestDate6();
//
// //int i = 0;
// //double d = 1.1;
// //cout << i; // cout.operator<<(i);
// //cout << d; // cout.operator<<(d);
//
// return 0;
//}
class A
{
public:
// 他们是默认成员函数,我们不写编译器会自动生成,自动生成就够用了,所以一般是不需要我们自己写的
// 特殊场景:不想让别人取到这个类型对象的地址
A* operator&()
{
return nullptr;
}
const A* operator&()const
{
return nullptr;
}
void Print() const
{
//_year = 1;
cout << _year << "/" << _month << "/" << _day << endl;
}
/*void Print()
{
_year = 1;
cout << _year << "/" << _month << "/" << _day << endl;
}*/
private:
int _year; // 年
int _month; // 月
int _day; // 日
};
int main()
{
A d1;
const A d2;
d1.Print();
d2.Print();
cout << &d1 << endl;
cout << &d2 << endl;
return 0;
}
2.const成员
将 const 修饰的 “ 成员函数 ” 称之为 const 成员函数 , const 修饰类成员函数,实际修饰该成员函数 隐含的 this 指针 ,表明在该成员函数中 不能对类的任何成员进行修改。

3.取地址及const取地址操作符重载
这两个默认成员函数一般不用重新定义 ,编译器默认会生成。
class Date
{
public :
Date* operator&()
{
return this ;
}
const Date* operator&()const
{
return this ;
}
private :
int _year ; // 年
int _month ; // 月
int _day ; // 日
};
这两个运算符一般不需要重载,使用编译器生成的默认取地址的重载即可,只有特殊情况,才需要 重载,比如想让别人获取到指定的内容!
4. 再谈构造函数
4.1 构造函数体赋值
在创建对象时,编译器通过调用构造函数,给对象中各个成员变量一个合适的初始值。
class Date
{
public:
Date(int year, int month, int day)
{
_year = year;
_month = month;
_day = day;
}
private:
int _year;
int _month;
int _day;
};
虽然上述构造函数调用之后,对象中已经有了一个初始值,但是不能将其称为对对象中成员变量的初始化, 构造函数体中的语句只能将其称为赋初值 ,而不能称作初始化。因为 初始化只能初始化一次,而构造函数体 内可以多次赋值 。
4.2 初始化列表
初始化列表:以一个 冒号开始 ,接着是一个以 逗号分隔的数据成员列表 ,每个 " 成员变量 " 后面跟一个 放在括 号中的初始值或表达式。
class Date
{
public:
Date(int year, int month, int day)
: _year(year)
, _month(month)
, _day(day)
{}
private:
int _year;
int _month;
int _day;
};
【注意】
- 每个成员变量在初始化列表中只能出现一次(初始化只能初始化一次)。
-
类中包含以下成员,必须放在初始化列表位置进行初始化:
- 引用成员变量
-
const 成员变量
-
自定义类型成员 ( 且该类没有默认构造函数时 )
-
尽量使用初始化列表初始化,因为不管你是否使用初始化列表,对于自定义类型成员变量,一定会先使用初始化列表初始化。
- 成员变量在类中声明次序就是其在初始化列表中的初始化顺序,与其在初始化列表中的先后次序无关。
4.3 explicit关键字
构造函数不仅可以构造与初始化对象, 对于单个参数或者除第一个参数无默认值其余均有默认值的构造函 数,还具有类型转换的作用 。
class Date
{
public:
// 1. 单参构造函数,没有使用explicit修饰,具有类型转换作用
// explicit修饰构造函数,禁止类型转换---explicit去掉之后,代码可以通过编译
explicit Date(int year)
:_year(year)
{}
/*
// 2. 虽然有多个参数,但是创建对象时后两个参数可以不传递,没有使用explicit修饰,具有类型转
换作用
// explicit修饰构造函数,禁止类型转换
explicit Date(int year, int month = 1, int day = 1)
: _year(year)
, _month(month)
, _day(day)
{}
*/
Date& operator=(const Date& d)
{
if (this != &d)
{
_year = d._year;
_month = d._month;
_day = d._day;
}
return *this;
}
private:
int _year;
int _month;
int _day;
};
void Test()
{
Date d1(2022);
// 用一个整形变量给日期类型对象赋值
// 实际编译器背后会用2023构造一个无名对象,最后用无名对象给d1对象进行赋值
d1 = 2023;
// 将1屏蔽掉,2放开时则编译失败,因为explicit修饰构造函数,禁止了单参构造函数类型转换的作用
}
上述代码可读性不是很好, 用 explicit 修饰构造函数,将会禁止构造函数的隐式转换 。
5. static成员
5.1 概念
声明为 static 的类成员 称为 类的静态成员 ,用 static 修饰的 成员变量 ,称之为 静态成员变量 ;用 static 修饰 的 成员函数 ,称之为 静态成员函数 。 静态成员变量一定要在类外进行初始化。
class A
{
public:
A()
{
++_scount;
}
A(const A& t)
{
++_scount;
}
~A()
{
--_scount;
}
//静态成员函数 -- 没有this指针
static int GetACount()
{
return _scount;
}
private:
static int _scount; //声明
};
//类外面定义初始化
int A::_scount = 0;
void TestA()
{
cout << A::GetACount() << endl;
A a1, a2;
A a3(a1);
cout << A::GetACount() << endl;
}
5.2 特性
- 静态成员为所有类对象所共享,不属于某个具体的对象,存放在静态区;
- 静态成员变量必须在类外定义,定义时不添加static关键字,类中只是声明 ;
- 类静态成员即可用 类名::静态成员 或者 对象.静态成员 来访问 ;
- 静态成员函数没有隐藏的this指针,不能访问任何非静态成员 ;
- 静态成员也是类的成员,受public、protected、private 访问限定符的限制。
6. 友元
友元提供了一种突破封装的方式,有时提供了便利。但是友元会增加耦合度,破坏了封装,所以友元不宜多用。
友元分为: 友元函数 和 友元类。
6.1 友元函数
问题:现在尝试去重载 operator<< ,然后发现没办法将 operator<< 重载成成员函数。 因为 cout 的输出流对 象和隐含的 this 指针在抢占第一个参数的位置 。 this 指针默认是第一个参数也就是左操作数了。但是实际使用中cout 需要是第一个形参对象,才能正常使用。所以要将 operator<< 重载成全局函数。但又会导致类外没办法访问成员,此时就需要友元来解决。operator>> 同理。
class Date
{
public:
Date(int year, int month, int day)
: _year(year)
, _month(month)
, _day(day)
{}
// d1 << cout; -> d1.operator<<(&d1, cout); 不符合常规调用
// 因为成员函数第一个参数一定是隐藏的this,所以d1必须放在<<的左侧
ostream& operator<<(ostream& _cout)
{
_cout << _year << "-" << _month << "-" << _day << endl;
return _cout;
}
private:
int _year;
int _month;
int _day;
};
友元函数 可以 直接访问 类的 私有 成员,它是 定义在类外部 的 普通函数 ,不属于任何类,但需要在类的内部声明,声明时需要加friend 关键字。
class Date
{
friend ostream& operator<<(ostream& _cout, const Date& d);
friend istream& operator>>(istream& _cin, Date& d);
public:
Date(int year = 1900, int month = 1, int day = 1)
: _year(year)
, _month(month)
, _day(day)
{}
private:
int _year;
int _month;
int _day;
};
ostream& operator<<(ostream& _cout, const Date& d) {
_cout << d._year << "-" << d._month << "-" << d._day;
return _cout;
}
istream& operator>>(istream& _cin, Date& d) {
_cin >> d._year;
_cin >> d._month;
_cin >> d._day;
return _cin;
}
int main()
{
Date d;
cin >> d;
cout << d << endl;
return 0;
}
-
友元函数 可访问类的私有和保护成员,但 不是类的成员函数;
-
友元函数 不能用 const 修饰;
-
友元函数 可以在类定义的任何地方声明, 不受类访问限定符限制 ;
-
一个函数可以是多个类的友元函数;
-
友元函数的调用与普通函数的调用原理相同。
6.2 友元类
友元类的所有成员函数都可以是另一个类的友元函数,都可以访问另一个类中的非公有成员。
-
友元关系是单向的,不具有交换性。比如上述Time 类和 Date 类,在 Time 类中声明 Date 类为其友元类,那么可以在 Date 类中直接访问 Time类的私有成员变量,但想在Time 类中访问 Date 类中私有的成员变量则不行。
-
友元关系不能传递 。如果B 是 A 的友元, C 是 B 的友元,则不能说明 C 时 A 的友元。
-
友元关系不能继承。
7. 内部类
概念: 如果一个类定义在另一个类的内部,这个内部类就叫做内部类 。内部类是一个独立的类,它不属于外部类,更不能通过外部类的对象去访问内部类的成员。外部类对内部类没有任何优越的访问权限。
注意: 内部类就是外部类的友元类 ,参见友元类的定义,内部类可以通过外部类的对象参数来访问外部类中的所有成员。但是外部类不是内部类的友元。
特性:
- 内部类可以定义在外部类的public、protected、private都是可以的。
- 注意内部类可以直接访问外部类中的static成员,不需要外部类的对象/类名。
- sizeof(外部类)=外部类,和内部类没有任何关系。
8.练习题
求1+2+3+...+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
int i = 1;
int sum = 0;
class Sum
{
public:
Sum()
{
sum += i;
++i;
}
};
class Solution {
public:
int Sum_Solution(int n) {
Sum a[n];//调用n次sum的构造函数
return sum;
}
};
根据输入的日期,计算是这一年的第几天。保证年份为4位数且日期合法。
#include <iostream>
using namespace std;
int main()
{
int year, month, day;
cin >> year >> month >> day;
//2012 12 31
int monthDays1_N[13] = { 0,31,59,90,120,151,181,212,243,273,304,334,365 };
//[1,month-1]
int n = monthDays1_N[month - 1] + day;
if (month > 2 &&( (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)))
n += 1;
return 0;
}
本文含有隐藏内容,请 开通VIP 后查看