类的6个默认成员函数
1。构造函数
作用:初始化变量
特征:
1。函数名与类名相同
2。无返回值
3。如果没有显式定义,自动生成
4。对象实例化时编译器自动调用
5。可重载
举例代码如下:
#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
using namespace std;
class Date
{
public:
void SetDate(int year,int month,int day)//构造函数
{
_year = year;
_month = month;
_day = day;
}
void Display()
{
cout << _year << "-" << _month << "-" << _day << endl;
}
private:
int _year;
int _month;
int _day;
};
int main()
{
Date d1;
d1.SetDate(2019, 9, 1);
d1.Display();
Date d2;
d2.SetDate(2019, 12, 1);
d2.Display();
return 0;
}
2。析构函数
作用:完成类的资源清理
特征:
1。函数名是在类名前加~
2。无参数无返回值
3。如果没有显示定义,编译器自动生成
4。对象生命周期结束时,编译器自动调用
实例代码如下:
#define _CRT_SECURE_NO_WARNINGS 1
typedef int DataType;
class SeqList
{
public:
SeqList(int capacity = 10)
{
_pData = (DataType*)malloc(capacity * sizeof(DataType));
assert(_pData);
_size = 0;
_capacity = capacity;
}
~SeqList()//析构函数
{
if (_pData)
{
free(_pData); // 释放堆上的空间
_pData = NULL; // 将指针置为空
_capacity = 0;
_size = 0;
}
}
private:
int* _pData;
size_t _size;
size_t _capacity;
};
3。拷贝构造函数
特征:
1。是构造函数的一种重载形式
2。只有一个参数且必须引用传参
实例代码如下:
#define _CRT_SECURE_NO_WARNINGS 1
class Date
{
public:
Date(int year = 1900, 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;
}
private:
int _year;
int _month;
int _day;
};
int main()
{
Date d1;
Date d2(d1);
return 0;
}
4。赋值运算符重载
(1)运算符的重载
作用:为了提高C++的可读性
函数原型:返回值类型 operator运算符(参数列表)
(2)赋值操作符重载
作用:对已存在的对象进行赋值拷贝
特征:
1。参数类型
2。返回值
3。返回 *this
4。检测是否自己给自己赋值
5。如果没有显式定义,则会自动生成,完成对象按字节序的值拷贝
实例代码如下:
class Date
{
public:
Date(int year = 1900, 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& 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;
};
5。const成员
作用:修饰成员函数里隐含的this指针
特征:不能对类的任何成员进行更改
实例代码如下:
#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
using namespace std;
class Date
{
public:
void Display()
{
cout << "Display ()" << endl;
cout << "year:" << _year << endl;
cout << "month:" << _month << endl;
cout << "day:" << _day << endl << endl;
}
void Display() const
{
cout << "Display () const" << endl;
cout << "year:" << _year << endl;
cout << "month:" << _month << endl;
cout << "day:" << _day << endl << endl;
}
private:
int _year; // 年
int _month; // 月
int _day; // 日
};
void Test()
{
Date d1;
d1.Display();
const Date d2;
d2.Display();
}
int main()
{
Test();
return 0;
}
6。取地址操作符重载和const修饰的取地址操作符重载
实例代码如下:
#define _CRT_SECURE_NO_WARNINGS 1
class Date
{
public:
Date* operator&()
{
return this;
}
const Date* operator&()const
{
return this;
}
private:
int _year; // 年
int _month; // 月
int _day; // 日
};
这两个操作符使用默认的取地址操作符重载即可。
本文详细介绍了C++中类与对象的6个默认成员函数:构造函数、析构函数、拷贝构造函数、赋值运算符重载、const成员以及取地址操作符重载。通过实例代码解析了每个函数的作用、特征和应用场景,帮助读者深入理解这些基本概念。
1153

被折叠的 条评论
为什么被折叠?



