【C++】类与对象(三)—— 类的新玩法

1. 再谈构造函数

1.1 构造函数体赋值

在创建对象时,编译器通过调用构造函数,给对象中各个成员变量一个合适的初始值。

class Date
{
public:
	Date(int year, int month, int day)
	{
		_year = year;
		_month = month;
		_day = day;
	}
private:
	int _year;
	int _month;
	int _day;
};

虽然上述构造函数调用之后,对象中已经有了一个初始值,但是不能将其称作为类对象成员的初始化,构造函数体中的语句只能将其称作为赋初值,而不能称作初始化。
因为初始化只能初始化一次,而构造函数体内可以多次赋值。

1.2 初始化列表

初始化列表:以一个冒号开始,接着是一个以逗号分隔的数据成员列表,每个"成员变量"后面跟一个放在括号中的初始值或表达式。

class Date
{
public:
	Date(int year, int month, int day)
		: _year(year)
		, _month(month)
		, _day(day)
	{}
private:
	int _year;
	int _month;
	int _day;
};

【注意】

  1. 每个成员变量在初始化列表中只能出现一次(初始化只能初始化一次)
  2. 类中包含以下成员,必须放在初始化列表位置进行初始化:
    引用成员变量,const成员变量,自定义类型成员(该类没有默认构造函数)
class A
{
public:
	A(int a)
		:_a(a)
	{}
private:
	int _a;
};
class B
{
public:
	B(int a, int ref)
		:_aobj(a)
		, _ref(ref)
		, _n(10)
	{}
private:
	A _aobj; // 没有默认构造函数
	int& _ref; // 引用
	const int _n; // const
};
  1. 尽量使用初始化列表初始化,因为不管你是否使用初始化列表,对于自定义类型成员变量,一定会先使用初始化列表初始化。

  2. 成员变量在类中声明次序就是其在初始化列表中的初始化顺序,与其在初始化列表中的先后次序无关。

1.3 explicit关键字

构造函数不仅可以构造与初始化对象,对于单个参数的构造函数,还具有类型转换的作用。

2. static成员

2.1 概念

声明为static的类成员称为类的静态成员,用static修饰的成员变量,称之为静态成员变量;用static修饰的成员函数,称之为静态成员函数。静态的成员变量一定要在类外进行初始化

class A
{
public:
	A() { ++_scount; }
	A(const A& t) { ++_scount; }
	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;
}

2.2 特性

  1. 静态成员为所有类对象所共享,不属于某个具体的实例
  2. 静态成员变量必须在类外定义,定义时不添加static关键字
  3. 类静态成员即可用类名::静态成员或者对象.静态成员来访问
  4. 静态成员函数没有隐藏的this指针,不能访问任何非静态成员
  5. 静态成员和类的普通成员一样,也有public、protected、private3种访问级别,也可以具有返回值

3.C++11 的成员初始化新玩法

C++11支持非静态成员变量在声明时进行初始化赋值,但是要注意这里不是初始化,这里是给声明的成员变量缺省值。

4. 友元

友元分为:友元函数和友元类
友元提供了一种突破封装的方式,有时提供了便利。但是友元会增加耦合度,破坏了封装,所以友元不宜多用。

4.1 友元函数

问题:现在我们尝试去重载operator<<,然后发现我们没办法将operator<<重载成成员函数。
因为cout的输出流对象和隐含的this指针在抢占第一个参数的位置。this指针默认是第一个参数也就是左操作数了。
但是实际使用中cout需要是第一个形参对象,才能正常使用。所以我们要将operator<<重载成全局函数。但是这样的话,又会导致类外没办法访问成员,那么这里就需要友元来解决operator>>同理。

友元函数可以直接访问类的私有成员,它是定义在类外部的普通函数,不属于任何类,但需要在类的内部声明,声明时需要加friend关键字。

说明:

  • 友元函数可访问类的私有和保护成员,但不是类的成员函数
  • 友元函数不能用const修饰
  • 友元函数可以在类定义的任何地方声明,不受类访问限定符限制
  • 一个函数可以是多个类的友元函数
  • 友元函数的调用与普通函数的调用和原理相同

4.2 友元类

友元类的所有成员函数都可以是另一个类的友元函数,都可以访问另一个类中的非公有成员。

  • 友元关系是单向的,不具有交换性。

比如上述Time类和Date类,在Time类中声明Date类为其友元类,那么可以在Date类中直接访问Time
类的私有成员变量,但想在Time类中访问Date类中私有的成员变量则不行。

  • 友元关系不能传递

如果B是A的友元,C是B的友元,则不能说明C时A的友元。

5.内部类

5.1概念及特性

概念:如果一个类定义在另一个类的内部,这个内部类就叫做内部类。注意此时这个内部类是一个独立的类,它不属于外部类,更不能通过外部类的对象去调用内部类。外部类对内部类没有任何优越的访问权限。

注意:内部类就是外部类的友元类。注意友元类的定义,内部类可以通过外部类的对象参数来访问外部类中的所有成员。但是外部类不是内部类的友元。

特性:

  1. 内部类可以定义在外部类的public、protected、private都是可以的。
  2. 注意内部类可以直接访问外部类中的static、枚举成员,不需要外部类的对象/类名。
  3. sizeof(外部类)=外部类,和内部类没有任何关系。

6.日期类的实现代码

// 日期类的实现
// 运算符重载作用:为了提高代码的可读性
// 函数重载:一些函数在相同作用域、函数名字相同、参数列表不同,与函数返回值类型是否相同无关
// 注意:哪些运算符不能重载?
class Date
{
public:
	// 全缺省的构造函数
	// 如果遇到非法的日期,将该日期构成默认的日期
	Date(int year = 1900, int month = 1, int day = 1)// 带上默认参数
		: _year(year)
		, _month(month)
		, _day(day)
	{
		if (!((year > 0) &&
			(month >= 1 && month <= 12) &&
			(day >= 1 && day <= GetMonthDay(year, month))))
		{
			_year = 1900;
			_month = 1;
			_day = 1;
		}
	}

	// 获取某年某月的天数
	int GetMonthDay(int year, int month)
	{
		int days[13] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
		if (month == 2)
		{
			// 检测该年是否为闰年
			if (isLeapYear(year))
				days[2] += 1;
		}
		return days[month];
	}

	bool isLeapYear(int year)const
	{
		// 四年一润百年不润,每四百年再一润
		if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))
		{
			return true;
		}
		return false;
	}

	// 拷贝构造函数
	Date(const Date& d)
		: _year(d._year)
		, _month(d._month)
		, _day(d._day)
	{}

	// 赋值运算符重载
	Date& operator=(const Date& d)
	{
		if (this != &d)
		{
			_year = d._year;
			_month = d._month;
			_day = d._day;
		}
		return *this;
	}

	// 析构函数
	~Date()
	{}

	friend ostream& operator<<(ostream& _cout, const Date& d);


	
	// 注意:复用之前重载的运算符,可以让代码实现起来更加的简单
	// >运算符重载
	bool 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;
		}
		return false;
	}

	// ==运算符重载
	bool operator==(const Date& d)const
	{
		return _year == d._year &&
			_month == d._month &&
			_day == d._day;
	}

	// 注意:==和!=是同时出现的
	// !=运算符重载
	bool operator != (const Date& d)const
	{
		return !(*this == d);
	}

	// >=运算符重载
	bool operator >= (const Date& d)
	{
		if (*this > d || *this == d)
			return true;
		return false;
	}

	// <运算符重载
	bool operator < (const Date& d)const
	{
		if (!(*this > d || *this == d))
			return true;
		return false;
	}

	// <=运算符重载
	bool operator <= (const Date& d)const
	{
		if (*this < d || *this == d)
			return true;
		return false;
	}


	
	// 日期+天数
	Date operator+(int days)
	{
		// 必须要将days加到当前对象上
		//_day += days;
		//return *this;
		// 注意:不能将天数加到当前对象上,因为+的左操作数就被修改了
		// 不符合+的规则

		if (days < 0)
		{
			return *this - (0 - days);
		}

		Date temp(*this);
		temp._day += days;

		// temp日期可能会非法:如果_day超过本年本月的天数,日期肯定会是非法的
		int daysOfMonths = 0;
		while (temp._day >(daysOfMonths = temp.GetMonthDay(temp._year, temp._month)))
		{
			temp._month += 1;
			if ((temp._month > 12))
			{
				temp._year += 1;
				temp._month = 1;
			}
			temp._day -= daysOfMonths;
		}
		return temp;
	}

	// 日期-天数
	Date operator-(int days)
	{
		if (days < 0)
		{
			return *this + (0 - days);
		}

		Date temp(*this);
		temp._day -= days;

		// temp日期非法
		while (temp._day <= 0)
		{
			temp._month -= 1;
			if (temp._month == 0)
			{
				temp._year -= 1;
				temp._month = 12;
			}
			temp._day += temp.GetMonthDay(temp._year, temp._month);
		}
		return temp;
	}

	// 前置++
	Date& operator++()
	{
		*this = *this + 1;
		return *this;
	}

	// 后置++
	Date operator++(int)
	{
		Date temp(*this);
		*this = *this + 1;
		return temp;
	}

	// 前置--
	Date& operator--()
	{
		*this = *this - 1;
		return *this;
	}

	// 后置--
	Date operator--(int)
	{
		Date temp(*this);
		*this = *this - 1;
		return temp;
	}

	// 日期-日期 返回天数
	// *this和d之间的差值
	int operator-(const Date& d)
	{
		Date minDate(*this);
		Date maxDate(d);
		if (minDate > maxDate)
		{
			minDate = d;
			maxDate = *this;
		}

		int count = 0;
		while (minDate != maxDate)
		{
			count++;
			minDate++;
		}

		return count;
	}

private:
	int _year;
	int _month;
	int _day;
};

// <<的重载
// 1.必须要重载成全局函数---因为它的第一个参数必须是ostream&
// 2.如果重载成成员函数,则其第一个参数就是this指针,调用是反的 d<<cout;
// 3.必须要有返回值,为了支持连续输出
// 4.在函数体中输出时,尽量避免一些格式化的操作,比如换行
ostream& operator<<(ostream& _cout, const Date& d)
{
	_cout << d._year << "-" << d._month << "-" << d._day;
	return _cout;
}

int main()
{
	Date d1(2020, 9, 20);
	Date d2;
	//d2 = d1 + 999;
	d2 = d1 - 999;
	cout << d1 << endl;
	cout << d2 << endl;

	Date d3(2020, 9, 100);
	cout << d3 << endl;

	Date d4(2021, 1, 1);
	cout << d1 - d4 << endl;
	return 0;
}

7. 再次理解封装

C++是基于面向对象的程序,面向对象有三大特性即:封装、继承、多态。

C++通过类,将一个对象的属性与行为结合在一起,使其更符合人们对于一件事物的认知,将属于该对象的所有东西打包在一起;通过访问限定符选择性的将其部分功能开放出来与其他对象进行交互,而对于对象内部的一些实现细节,外部用户不需要知道,知道了有些情况下也没用,反而增加了使用或者维护的难度,让整个事情复杂化。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值