以日期为例,我们创造一个日期类,进行构造、拷贝构造、析构、赋值运算符重载操作
test.h
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)//避免this指针指向的地址与d的地址相同,即避免自己给自己赋值的情况
{
_year = d._year;
_month = d._month;
_day = d._day;
}
return *this;
}
void Show()
{
cout << _year << "-" << _month << "-" << _day << endl;
}
~Date()
{
}
private:
int _year;
int _month;
int _day;
};
void TestDate()
{
Date d1(1996, 5, 8);
Date d2(d1);
Date d3(1996, 4, 27);
d2 = d3;
d1.Show();
d2.Show();
}
text.c
#include <iostream>
using namespace std;
#include "test.h"
int main()
{
TestDate();
system("pause");
return 0;
}