类和对象中

一.构造函数

构造函数是特殊的成员函数,需要注意的是,构造函数虽然名称叫构造,但是构造函数的主要任务并不是开空间创建对象(我们常使⽤的局部对象是栈帧创建时,空间就开好了),而是对象实例化时初始化对象,类似于完成Init的功能。

构造函数有许多特性,这些特性能帮助我们理解类的默认成员函数。

1.函数名与类名相同.

2.无返回值。(返回值啥都不需要给,也不需要写void,不要纠结,C++规定如此)

3.对象实例化时系统会自动调用对应的构造函数

4.构造函数可以重载

5.如果类中没有显式定义构造函数,则C++编译器会自动生成⼀个无参的默认构造函数,一旦用户显式定义编译器将不再生成

6.无参构造函数、全缺省构造函数、我们不写构造时编译器默认生成的构造函数,都叫做默认构造函 数。但是这三个函数有且只有一个存在,不能同时存在。无参构造函数和全缺省构造函数虽然构成函数重载,但是调用时会存在歧义。要注意很多同学会认为默认构造函数是编译器默认生成那个叫默认构造,实际上无参构造函数、全缺省构造函数也是默认构造,总结⼀下就是不传实参就可以调用的构造就叫默认构造

7.我们不写,编译器默认生成的构造,对内置类型成员变量的初始化没有要求,也就是说是是否初始 化是不确定的,看编译器。对于自定义类型成员变量,要求调用这个成员变量的默认构造函数初始 化。如果这个成员变量,没有默认构造函数,那么就会报错,我们要初始化这个成员变量,需要用初始化列表才能解决

#include<iostream>
using namespace std;

class Date
{
public:
 // 1.⽆参构造函数 
 Date()
 {
 _year = 1;
 _month = 1;
 _day = 1;
 }
 // 2.带参构造函数 
 Date(int year, int month, int day)
 {
 _year = year;
 _month = month;
 _day = day;
 }
 // 3.全缺省构造函数 
 /*Date(int year = 1, int month = 1, int day = 1)
 {
 _year = year;
 _month = month;
 _day = day;
 }*/
 void Print()
 {
 cout << _year << "/" << _month << "/" << _day << endl;
}
private:
 int _year;
 int _month;
 int _day;
};

int main()
{
 // 如果留下三个构造中的第⼆个带参构造,第⼀个和第三个注释掉 
 // 编译报错:error C2512: “Date”: 没有合适的默认构造函数可⽤ 
 Date d1; // 调⽤默认构造函数 
 Date d2(2025, 1, 1); // 调⽤带参的构造函数 
 // 注意:如果通过⽆参构造函数创建对象时,对象后⾯不⽤跟括号,否则编译器⽆法 
 // 区分这⾥是函数声明还是实例化对象  
 Date d3();
 d1.Print();
 d2.Print();
 return 0;
}

二.析构函数

析构函数与构造函数功能相反,析构函数不是完成对对象本身的销毁,比如局部对象是存在栈帧的, 函数结束栈帧销毁,他就释放了,不需要我们管,C++规定对象在销毁时会自动调用析构函数,完成对象中资源的清理释放工作。类似于完成Destroy的功能

同理析构函数也有很多特性需要我们去了解

1.析构函数名是在类名前加上字符~

2.无参数无返回值。(这里跟构造类似,也不需要加void)

3.⼀个类只能有⼀个析构函数。若未显式定义,系统会自动生成默认的析构函数

4.对象生命周期结束时,系统会自动调用析构函数

5.跟构造函数类似,我们不写编译器自动生成的析构函数对内置类型成员不做处理,自定类型成员会 调用他的析构函数

6.还需要注意的是我们显示写析构函数,对于自定义类型成员也会调用他的析构,也就是说自定义类型成员无论什么情况都会自动调用析构函数

7.如果类中没有申请资源时,析构函数可以不写,直接使用编译器生成的默认析构函数,如Date;如 果默认生成的析构就可以用,也就不需要显示写析构,但是有资源申请时,⼀定要自己写析构,否则会造成资源泄漏,如Stack

8.⼀个局部域的多个对象,C++规定后定义的先析构

class Stack
{
public:
 Stack(int n = 4)
 {
 _a = (STDataType*)malloc(sizeof(STDataType) * n);
 if (nullptr == _a)
 {
 perror("malloc申请空间失败");
 return;
 }
 _capacity = n;
 _top = 0;
 }

//这就是析构函数会在对象生命周期结束时调用
 ~Stack()
 {
 cout << "~Stack()" << endl;
 free(_a);
 _a = nullptr;
 _top = _capacity = 0;
 }
private:
 STDataType* _a;
 size_t _capacity;
 size_t _top;
};

三.拷贝构造函数

如果⼀个构造函数的第⼀个参数是自身类类型的引用,且任何额外的参数都有默认值,则此构造函数 也叫做拷贝构造函数,也就是说拷贝构造是⼀个特殊的构造函数。

同理拷贝构造函数也有很多特性需要我们去了解

1.拷贝构造函数是构造函数的⼀个重载

2.拷贝构造函数的参数只有⼀个且必须是类类型对象的引用,使用传值方式编译器直接报错,因为语 法逻辑上会引发无穷递归调用,下面这张图方便理解

3.C++规定⾃定义类型对象进行拷贝行为必须调用拷贝构造,所以这里自定义类型传值传参和传值返 回都会调用拷贝构造完成

4.若未显式定义拷贝构造,编译器会生成自动生成拷贝构造函数。自动生成的拷贝构造对内置类型成 员变量会完成值拷贝/浅拷贝(⼀个字节⼀个字节的拷贝),对自定义类型成员变量会调用他的拷贝构造。

5.传值返回会产生⼀个临时对象调用拷贝构造,传值引用返回,返回的是返回对象的别名(引用),没有产生拷贝。但是如果返回对象是⼀个当前函数局部域的局部对象,函数结束就销毁了,那么使用引用返回是有问题的,这时的引用相当于⼀个野引用,类似⼀个野指针⼀样。传引用返回可以减少拷贝,但是⼀定要确保返回对象,在当前函数结束后还在,才能用引用返回

6.对于Date类默认生成的拷贝构造就够用,就不需要再写,对于栈这种有指向空间资源的就必须自己实现,具体情况要具体分析

#include<iostream>
using namespace std;

class Date
{
public:
 Date(int year = 1, int month = 1, int day = 1)
 {
 _year = year;
 _month = month;
 _day = day;
 }
 // 编译报错:error C2652: “Date”: ⾮法的复制构造函数: 第⼀个参数不应是“Date” 
 //Date(Date d)
 Date(const Date& d)
 {
 _year = d._year;
 _month = d._month;
 _day = d._day;
 }
 Date(Date* d)
 {
 _year = d->_year;
 _month = d->_month;
 _day = d->_day;
 }
 void Print()
 {
 cout << _year << "-" << _month << "-" << _day << endl;
 }
private:
 int _year;
 int _month;
 int _day;
};

void Func1(Date d)
{
 cout << &d << endl;
 d.Print();
}

// Date Func2()
Date& Func2()
{
 Date tmp(2024, 7, 5);
 tmp.Print();
 return tmp;
}

int main()
{
 Date d1(2024, 7, 5);
 // C++规定⾃定义类型对象进⾏拷⻉⾏为必须调⽤拷⻉构造,所以这⾥传值传参要调⽤拷⻉
构造 
 // 所以这⾥的d1传值传参给d要调⽤拷⻉构造完成拷⻉,传引⽤传参可以较少这⾥的拷⻉ 
 Func1(d1);
 cout << &d1 << endl;
 // 这⾥可以完成拷⻉,但是不是拷⻉构造,只是⼀个普通的构造 
 Date d2(&d1);
 d1.Print();
 d2.Print();
 //这样写才是拷⻉构造,通过同类型的对象初始化构造,⽽不是指针 
 Date d3(d1);
 d2.Print();
 // 也可以这样写,这⾥也是拷⻉构造 
 Date d4 = d1;
 d2.Print();
 
 // Func2返回了⼀个局部对象tmp的引⽤作为返回值 
 // Func2函数结束,tmp对象就销毁了,相当于了⼀个野引⽤ 
 Date ret = Func2();
 ret.Print();
 
 return 0;
}

四.赋值运算符重载

1.运算符重载

当运算符被用于类类型的对象时,C++语言允许我们通过运算符重载的形式指定新的含义。C++规 定类类型对象使用运算符时,必须转换成调用对应运算符重载,若没有对应的运算符重载,则会编 译报错

运算符重载是具有特名字的函数,他的名字是由operator和后面要定义的运算符共同构成。和其他 函数⼀样,它也具有其返回类型和参数列表以及函数体

重载运算符函数的参数个数和该运算符作用的运算对象数量⼀样多。⼀元运算符有⼀个参数,二元 运算符有两个参数,二元运算符的左侧运算对象传给第⼀个参数,右侧运算对象传给第二个参数

如果一个重载运算符函数是成员函数,则它的第⼀个运算对象默认传给隐式的this指针,因此运算 符重载作为成员函数时,参数比运算对象少⼀个

重载++运算符时,有前置++和后置++,运算符重载函数名都是operator++,无法很好的区分。 C++规定,后置++重载时,增加⼀个int形参,跟前置++构成函数重载,方便区分

重载<< >> 时若将其重载为成员函数会导致调用时需按 对象<<cout 的方式去调用,这样不符合我们的书写习惯,所以应将他们重载成全局函数才得以解决问题。


#include<iostream>
using namespace std;

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

 void Print()
 {
 cout << _year << "-" << _month << "-" << _day << endl;
 }

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

// 重载为全局的⾯临对象访问私有成员变量的问题 
// 有⼏种⽅法可以解决: 
// 1、成员放公有  
// 2、Date提供getxxx函数 
// 3、友元函数 
// 4、重载为成员函数 

bool operator==(const Date& d1, const Date& d2)
{
 return d1._year == d2._year
 && d1._month == d2._month
 && d1._day == d2._day;
}

int main()
{
 Date d1(2024, 7, 5);
 Date d2(2024, 7, 6);
 // 运算符重载函数可以显⽰调⽤ 
 operator==(d1, d2);
 // 编译器会转换成 operator==(d1, d2); 
 d1 == d2;
 return 0;
}
#include<iostream>
using namespace std;

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

 void Print()
 {
 cout << _year << "-" << _month << "-" << _day << endl;
 }

 bool operator==(const Date& d)
 {
 return _year == d._year
 && _month == d._month
 && _day == d._day;
 }

 Date& operator++()
 {
 cout << "前置++" << endl;
 //...
 return *this;
 }

 Date operator++(int)
 {
 Date tmp;
 cout << "后置++" << endl;
 //...
 return tmp;
 }
private:
 int _year;
 int _month;
 int _day;
};

int main()
{
 Date d1(2024, 7, 5);
 Date d2(2024, 7, 6);
 // 运算符重载函数可以显⽰调⽤ 
 d1.operator==(d2);
 // 编译器会转换成 d1.operator==(d2); 
 d1 == d2;
 // 编译器会转换成 d1.operator++(); 
 ++d1;
 // 编译器会转换成 d1.operator++(0); 
 d1++;
 return 0;
}

2.赋值运算符重载

赋值运算符重载是⼀个默认成员函数,用于完成两个已经存在的对象直接的拷贝赋值,这里要注意跟拷贝构造区分,拷贝构造用于⼀个对象拷贝初始化给另⼀个要创建的对象

同理赋值运算符重载也有很多特性需要我们去了解

a.赋值运算符重载是⼀个运算符重载,规定必须重载为成员函数。赋值运算重载的参数建议写成 const当前类类型引用,否则会传值传参会有拷贝

b.有返回值,且建议写成当前类类型引⽤,引用返回可以提高效率,有返回值目的是为了支持连续赋值场景

c.没有显式实现时,编译器会自动生成⼀个默认赋值运算符重载,默认赋值运算符重载行为跟默认构 造函数类似,对内置类型成员变量会完成值拷贝/浅拷贝(⼀个字节⼀个字节的拷贝),对自定义类型成员变量会调用他的拷贝构造

d.像Date这样的类成员变量全是内置类型且没有指向什么资源,编译器自动生成的赋值运算符重载就 可以完成需要的拷贝,所以不需要我们显示实现赋值运算符重载。像Stack这样的类,虽然也都是 内置类型,但是_a指向了资源,编译器自动生成的赋值运算符重载完成的值拷贝/浅拷贝不符合我们的需求,所以需要我们自己实现深拷贝(对指向的资源也进行拷贝)。

class Date
{
public:
 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 = d2;
 Date& operator=(const Date& d)
 {
 // 不要检查⾃⼰给⾃⼰赋值的情况 
 if (this != &d)
 {
 _year = d._year;
 _month = d._month;
 _day = d._day;
 }
 // d1 = d2表达式的返回对象应该为d1,也就是*this 
 return *this;
 }

 void Print()
 {
 cout << _year << "-" << _month << "-" << _day << endl;
 }
private:
 int _year;
 int _month;
 int _day;
};

int main()
{
Date d1(2024, 7, 5);
 Date d2(d1);
 Date d3(2024, 7, 6);
 d1 = d3;
 // 需要注意这⾥是拷⻉构造,不是赋值重载 
 // 请牢牢记住赋值重载完成两个已经存在的对象直接的拷⻉赋值 
 // ⽽拷⻉构造⽤于⼀个对象拷⻉初始化给另⼀个要创建的对象 
 Date d4 = d1;

 return 0;
}

五.const成员函数

将const修饰的成员函数称之为const成员函数,const修饰成员函数放到成员函数参数列表的后 面。const实际修饰该成员函数隐含的this指针,表明在该成员函数中不能对类的任何成员进行修改。const修饰Date类的Print成员函数,Print隐含的this指针由 Date* const this 变为 const Date* const this

#include<iostream>
using namespace std;

class Date
{
public:
 Date(int year = 1, int month = 1, int day = 1)
 {
 _year = year;
 _month = month;
 _day = day;
 }
 // void Print(const Date* const this) const
 void Print() const
 {
 cout << _year << "-" << _month << "-" << _day << endl;
 }
private:
 int _year;
 int _month;
 int _day;
};

int main()
{
 // 这⾥⾮const对象也可以调⽤const成员函数是⼀种权限的缩⼩ 
 Date d1(2024, 7, 5);
 d1.Print();
 const Date d2(2024, 8, 5);
 d2.Print();

 return 0;
}

六.取地址运算符重载

取地址运算符重载分为普通取地址运算符重载和const取地址运算符重载,⼀般这两个函数编译器⾃动 ⽣成的就可以够我们⽤了,不需要去显⽰实现。所以基本上我们在写代码的时候不用管这一点,当然也有些极为特殊的时候需要我们自己去实现,那我们就具体情况具体分析就行了。

class Date
{ 
public :
 Date* operator&()
 {
 return this;
 // return nullptr;
 }

 const Date* operator&()const
 {
 return this;
 // return nullptr;
 }
private :
 int _year ; // 年 
 int _month ; // ⽉ 
 int _day ; // ⽇ 
};

七.日期类的实现

我们可以自己实现一个非常基础但非常有助于初学者实践和掌握类和对象这一块知识的小练习。这个就是去实现一个日期类

Date.h

#include<iostream>
using namespace std;

class Date
{
	friend ostream& operator<<(ostream& out,const Date& d);

	friend istream& operator>>(istream& in, Date& d);

public:
	void Print() const;

	Date(int year = 1900, int month = 100, int day = 100);

    //类里面的成员函数默认为内联函数,对于GetMonthDay这类短小而频繁调用的成员函数就可以直接定
    //义在类里面,有助于提升效率
	int GetMonthDay(int year,int month)
	{
		static int arr[13] = {-1,31,28,31,30,31,30,31,31,30,31,30,31};
		if (2 == month && ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)))
		{
			return 29;
		}
		return arr[month];
	}

	Date& operator+=(int day);

	Date operator+(int day);

	Date& operator-=(int day);

	Date operator-(int day);

	bool operator<(const Date& d);

	bool operator<=(const Date& d);

	bool operator>(const Date& d);

	bool operator>=(const Date& d);

	bool operator==(const Date& d);

	bool operator!=(const Date& d);

	Date& operator++();

	Date operator++(int);

	int operator-(const Date& d);

	bool CheckDate();


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

ostream& operator<<(ostream& out,const Date& d);

istream& operator>>(istream& in,Date& d);

Date.cpp

#include"Date.h"

void Date::Print() const
{
	cout << _year << ' ' << _month << ' ' << _day << endl;
}

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

Date& Date::operator+=(int day)
{
	_day += day;
	while (_day > GetMonthDay(_year,_month))
	{
		_day -= GetMonthDay(_year,_month);
		_month += 1;
		if (13 == _month)
		{
			_month = 1;
			_year += 1;
		}
	}
	return *this;
}

Date Date::operator+(int day)
{
	Date temp = *this;
	temp += day;
	return temp;
}

Date& Date::operator-=(int day)
{
	_day -= day;
	while (_day <= 0)
	{
		_month--;
		if (0 == _month)
		{
			_year--;
			_month = 12;
		}
		_day += GetMonthDay(_year,_month);
	}
	return *this;
}

Date Date::operator-(int day)
{
	Date temp = *this;
	temp -= day;
	return temp;
}




bool Date::operator<(const Date& d)
{
	if (_year < d._year)
	{
		return true;
	}
	else if (_year == d._year)
	{
		if (_month < d._month)
		{
			return true;
		}
		else if (_month == d._month)
		{
			return _day < d._day;
		}
	}
	return false;
}

bool Date::operator<=(const Date& d)
{
	return (*this < d) || (*this == d);
}


bool Date::operator>(const Date& d)
{
	return !(*this <= d);
}

bool Date::operator>=(const Date& d)
{
	return !(*this < d);
}


bool Date::operator==(const Date& d)
{
	return ((_year == d._year) &&
		(_month == d._month) &&
		(_day == d._day));
}

bool Date::operator!=(const Date& d)
{
	return !(*this == d);
}

Date& Date::operator++()
{
	return *this += 1;
}

Date Date::operator++(int)
{
	Date temp = *this;
	*this += 1;
	return temp;
}

int Date::operator-(const Date& d)
{
	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;
}

bool Date::CheckDate()
{
	if (_month <= 0 || _month >= 13 || _day <= 0 || _day > GetMonthDay(_year, _month))
	{
		return false;
	}
	return true;
}

ostream& operator<<(ostream& out, const Date& d)
{
	out << d._year << "年" << d._month << "月" << d._day << "日" << endl;
	return out;
}

istream& operator>>(istream& in, Date& d)
{
	while (1)
	{
		cout << "请输入年月日" << endl;
		in >> d._year >> d._month >> d._day;
		if (d.CheckDate())
		{
			break;
		}
		else
		{
			cout << "日期非法请重新输入" << endl;
		}
	}
	return in;
}

  • 15
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值