C++:类与对象(中)

目录

1.默认成员函数

2.构造函数

3.析构函数 

 4.拷贝构造函数

5.运算符重载

5.1运算符重载

 5.2赋值运算符重载


1.默认成员函数

默认成员函数就是用户没有显式实现,编译器会自动生成的成员函数称为默认成员函数。一个类,我们不写的情况下编译器会默认以下6个成员函数,需要注意的是这6个中最重要的是前4个,最后两个取地址重载不重要。其次就是C++11以后还会增加两个默认成员函数,移动构造和移动赋值。

2.构造函数

构造函数时特殊的成员函数,需要注意的是,构造函数虽然名称叫构造,但是构造函数的主要任务并不是开空间创建对象(我们常使用的局部对象是函数栈帧创建时,空间就开好了),而是对象实例化时初始化对象。构造函数的本质是要代替我们以前Stack和Date类中写的Init函数功能,构造函数自动调用的特点就完美的替代了Init。

 

#include<iostream>
using namespace std;
class Date
{
public:
	//无参构造函数
	Date()
	{
		_year = 1;
		_month =1;
		_day = 1;
	}
	//带参构造函数
	Date(int year, int month, int day)
	{
		_year = year;
		_month = month;
		_day = day;
	}
	//全缺省构造函数
	//Date(int year = 1990, 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()
{
	Date d1;//调用默认构造函数

	Date d2(2024,8,23);//调用带参构造函数
	

	//注意:如果通过无参函数创建对象时,对象后面不用跟括号,否则编译器无法区分这里是函数声明还是实例化对象
	Date d3();




	d1.Print();
	d2.Print();



	return 0;
}
#include<iostream>
using namespace std;

typedef int	STDateType;
class Stack
{
public:
	//构造函数
	Stack(int n = 4)
	{
		_arr = (STDateType*)malloc(sizeof(STDateType) * n);
		if (_arr == nullptr)
		{
			perror("malloc fail!");
			exit(1);
		}
		_capacity = n;
		_top = 0;
	}
private:
	STDateType* _arr;
	int _capacity;
	int _top;
};

//两个Stack实现队列
class Myqueue
{
public:
	//编译器默认生成MyQueue的构造函数调用的是Stack的构造,完成的两个成员的初始化
private:
	Stack pushst;
	Stack popst;
};

int main()
{
	Myqueue mq;
	return 0;
}

3.析构函数 

析构函数的功能与构造函数刚好相反,析构函数不是完成对对象本身的销毁,比如局部对象存在函数栈帧的,函数结束栈帧销毁,他就释放了,这不需要我们管。C++规定对象在销毁时会自动调用析构函数,完成对象中资源清理释放工作相当于我们之前数据结构中的Destroy功能。注意只有申请了资源才需要释放,像Date类没有申请资源的不需要析构函数。

析构函数的特点:

 

#include<iostream>
using namespace std;

typedef int	STDateType;
class Stack
{
public:
	//构造函数
	Stack(int n = 4)
	{
		_arr = (STDateType*)malloc(sizeof(STDateType) * n);
		if (_arr == nullptr)
		{
			perror("malloc fail!");
			exit(1);
		}
		_capacity = n;
		_top = 0;
	}
	//析构函数
	~Stack()
	{
		cout << "~Stack()" << endl;
		free(_arr);
		_arr = nullptr;
		_capacity = _top = 0;
	}
private:
	STDateType* _arr;
	int _capacity;
	int _top;
};

//两个Stack实现队列
class Myqueue
{
public:
	//编译器默认生成MyQueue的构造函数调用的是Stack的构造,完成的两个成员的初始化

	//即使写了析构,也会自动调用Stack的析构
	//~Myqueue()
	//{

	//}
private:
	Stack pushst;
	Stack popst;
};

int main()
{
	Stack st;
	Myqueue mq;
	return 0;
}

C++中的构造函数和析构函数的应用在我们写代码的时候比C语言方便许多。

举个例子:括号匹配问题

C语言方法实现:

bool isValid(char* s) {
    //初始化
    ST st;
    STInite(&st);
    //遍历字符串s
    char* ps=s;
    while(*ps!='\0')
    {

        if((*ps=='{')||
        (*ps=='[')||
         (*ps=='('))
         {
            //左括号,入栈
            STPush(&st,*ps);
         }
         else
         {
            //如果只有一个括号,直接返回false
            if(STEmpty(&st))
            {
                return false;
            }
            //栈不为空才能取出元素
            char tmp=STTop(&st);
            if((tmp=='('&&*ps==')')||
            (tmp=='['&&*ps==']')||
            (tmp=='{'&&*ps=='}'))
                {
                    //出栈
                    STPop(&st);
                }
                else
                {
                    STDestroy(&st);
                    //不匹配
                    return false;
                }
         }
         ps++;
    }
    bool ret=STEmpty(&st)==true;
    //销毁
    STDestroy(&st);
    return ret;
}

C++实现: 

bool isValid(char* s)
{
	Stack st;
	while (*s)
	{
		//是左括号就入栈
		if (*s == '[' || *s == '(' || *s = '{')
		{
			st.Push(*s);
		}
		else
		{
			//右括号比左括号多
			if (st.Empty())
			{
				return false;
			}
			//从栈里面取左括号开始匹配
			char top = st.Top();
			st.Pop();

			//顺序错误
			if ((*s == ']' && *s != '[') || (*s == '}' && *s != '{') || (*s == ')' && *s != '('))
			{
				return false;
			}
		}
		s++;
	}
	return st.Empty();
}

 4.拷贝构造函数

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

拷贝构造的特点:

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

2.拷贝构造函数的第一个参数必须是类类型对象的引用,使用传值的方式编译器直接报错,因为语法逻辑会引发无穷递归。拷贝构造函数也可以多个参数,但是第一个参数必须是类类型的引用,后面的参数必须是缺省值。

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

4.若未显示定义拷贝构造,编译器会自动生成拷贝构造函数。自动生成的拷贝构造对内置类型成员变量会完成值拷贝 ,对自定义类型成员变量会调用他的拷贝构造。

5.只有申请了资源的类才需要些拷贝构造,像日期类这种没有申请资源且内置成员变量全都是内置类型不需要我们显示实现拷贝构造。像MyQueue这种类型内部是自定义类型Stack成员,则编译器会自动调用Stack的拷贝构造函数。有个小技巧,如果一个类显示实现了析构并释放了资源,那么他就需要显示拷贝构造。

6.传值返回会产生一个临时对象调用拷贝构造,传值引用返回,返回的是返回对象的别名,没有产生拷贝。但是如果返回的对象是当前函数局部域的局部对象,函数结束就销毁了,那么使用引用返回就会造成,野引用。传值返回可以减少拷贝,但是有可能会造成野引用。

#include<iostream>
using namespace std;
class Date
{
public:
	Date(int year = 1990, int month = 1, int day = 1)
	{
		_year = year;
		_month = month;
		_day = day;
	}

	//拷贝构造,传引用
	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 tmp(2024, 7, 5);
	tmp.Print();
	return tmp;
}



int main()
{
	Date d1(2024, 8, 23);//调用构造函数

	Func1(d1);//这里通过d1传值给d调用拷贝构造完成,传引用的话可以减少这里的拷贝
	cout << &d1 << endl;

	Date d2 = d1;//拷贝构造

	Date d3(&d1);//这里可以完成拷贝,但是不是拷贝构造,就是个普通的构造

	Date ret = Func2();//因为函数返回的是局部对象的引用,会造成野引用
	ret.Print();


	d1.Print();
	d2.Print();
	d3.Print();
	return 0;
}
#include<iostream>
using namespace std;
typedef int STDataType;
class Stack
{
public:
	Stack(int n = 4)
	{
		_a = (STDataType*)malloc(sizeof(STDataType) * n);
		if (nullptr == _a)
		{
			perror("malloc申请空间失败");
			return;
		}
		_capacity = n;
		_top = 0;
	}
	Stack(const Stack& st)
	{
		// 需要对_a指向资源创建同样⼤的资源再拷⻉值
		_a = (STDataType*)malloc(sizeof(STDataType) * st._capacity);
		if (nullptr == _a)
		{
			perror("malloc申请空间失败!!!");
			return;
		}
		memcpy(_a, st._a, sizeof(STDataType) * st._top);
		_top = st._top;
		_capacity = st._capacity;
	}
	void Push(STDataType x)
	{
		if (_top == _capacity)
		{
			int newcapacity = _capacity * 2;
			STDataType* tmp = (STDataType*)realloc(_a, newcapacity *
				sizeof(STDataType));
			if (tmp == NULL)
			{
				perror("realloc fail");
				return;
			}
			_a = tmp;
			_capacity = newcapacity;
		}
		_a[_top++] = x;
	}
	~Stack()
	{
		cout << "~Stack()" << endl;
		free(_a);
		_a = nullptr;
		_top = _capacity = 0;
	}
private:
	STDataType* _a;
	size_t _capacity;
	size_t _top;
};

// 两个Stack实现队列
class MyQueue
{
public:
private:
	Stack pushst;
	Stack popst;
};
int main()
{
	Stack st1;
	st1.Push(1);
	st1.Push(2);
	// Stack不显⽰实现拷⻉构造,⽤⾃动⽣成的拷⻉构造完成浅拷⻉
	// 会导致st1和st2⾥⾯的_a指针指向同⼀块资源,析构时会析构两次,程序崩溃
	Stack st2 = st1;
	MyQueue mq1;
	// MyQueue⾃动⽣成的拷⻉构造,会⾃动调⽤Stack拷⻉构造完成pushst/popst
	// 的拷⻉,只要Stack拷⻉构造⾃⼰实现了深拷⻉,他就没问题
	MyQueue mq2 = mq1;
	return 0;
}

5.运算符重载

5.1运算符重载

举个例子:

#include<iostream>
using namespace std;
class Date
{
public:
	Date(int year = 1990, int month = 1, int day = 1)
	{
		_year = year;
		_month = month;
		_day = day;
	}

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


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


int main()
{
	Date d1(2024, 8, 23);
	Date d2(2024, 8, 20);
	//运算符重载函数可以显示调用
	d1.operator==(d2);

	d1 == d2;//编译器会自动转换成d1.operator==(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;
}

 5.2赋值运算符重载

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

 

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

	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;
};

int main()
{
	Date d1(2024, 5, 6);
	Date d2(2024, 6, 6);

	d1 = d2;
	d1.Print();

	return 0;
}

  • 18
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值