一、类中的构造函数
在这里我们先简单插入一段c++代码块,下面是一个日期类对象
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=1;
int _month=1;
int _day=1;
};
int main()
{
Date d1;
Date d2(2023, 1, 1);
d1.Print();
d2.Print();
return 0;
在写c语言时,通常会写init函数进行初始化,在c++中,构造函数有如下特点:
1.构造函数功能跟init函数一样,起到初始化的作用
2.函数名和类名相同
3.没有返回值
4.对象实例化时,自动调用(最重要的)
5.一个类可以有多个构造函数
6.构造函数不创造对象,有多种初始化方式
7.全缺省和无参构造函数只能留一个
二、析构函数
析构函数特点如下:
1.析构函数完成清理资源
2.在类名前加~
3.无参数返回值类型
4.只有一个析构函数,所以析构函数不能重载,若未定义系统会自动生成析构函数
5.对象生命结束是会自动调用
下面是一段有关栈的类的使用
class Stack
{
public:
Stack()
{
_a = NULL;
_size = _capacity = 0;
}
Stack(int n)
{
_a = (int*)malloc(sizeof(int) * n);
if (nullptr == _a)
{
printf("malloc失败");
return;
}
_capacity = n;
_size = 0;
}
void Push(int x)
{
_a[_size++] = x;
}
~Stack()
{
free(_a);
_a = nullptr;
_size = _capacity = 0;
}
private:
//成员变量
int* _a;
int _size;
int _capacity;
}
void Push(int x)
{
_a[size++] = x;
}
int main()
{
Stack st(4);
st.Push(1);
return 0;
}
可以看到~Stack()析构函数的使用
三.运算符重载
首先需要知道运算符重载的作用那就是:使自定义类型对象可以使用运算符。
其中涉及operaor关键字
class Date
{
public:
Date(int year = 1, int month = 1, int day = 1)
{
_year = year;
_month = month;
_day = day;
}
bool operator==(const Date& d2)
{
return _year == d2._year;//隐藏
}//可以看到形参比操作数少一个
private:
int _year;
int _month;
int _day;
};
int main()
{
Date d1(2000, 1, 1);
Date d2(2001, 1, 1);
operator==(d1, d2);
d1 == d2;//转换成去调用operator函数
d1.operator==(d2);
cout << (d1 == d2) << endl;//<<
//d1 < d2;//自定义类型不能直接使用这些运算符
return 0;
}
重载运算符的函数名一般由 “operator” 关键字后跟运算符号来命名,如上面的==运算符重载,其中
重载的操作符必须有一个类类型的参数
作为类成员函数重载时,其形参看起来要比操作数数目少一个,因为成员函数的第一个参数为隐藏的this,那么就可以直接看作在类中使用私用变量来使用,减去或加上传入的那个参数
总结
本次简单总结一下类中的运算符重载,构造函数,析构函数。