#include
#include<stdio.h>
using namespace std;
class Date
{
public:
//void Display(Date* const this) 始终指向当前调用此函数的对象,指向不会发生改变
//this指针类型:类类型 *const
//this指针只存在于成员函数中
//this始终作为成员函数的第一个形参
//编译器自动传递,不需要显式定义这个参数
//this 不是类的成员,只是一个函数形参,一般存在栈上,一般会做优化,存在寄存器中
void Display()
{
cout << this->_year << “-” << this->_month << “-” <_day << endl;
//this = nullptr;
this->_year = 2022;
}
void SetDate(int year, int month, int day)
{
_year = year;
_month = month;
_day = day;
}
void fun1()
{
cout << “Date::fun1()” << endl;
}
private:
int _year;
int _month;
int _day;
};
void fun3()
{
}
class AA
{
//6个成员函数
public:
AA(int a=1)
{
}
};
class Date
{
public:
//构造函数:函数名和类名相同 无返回值 可以重载,编译器在创建时自动调用
//只有当类没有定义任何构造函数时,编译器才会自动生成一个无参构造
//如果类中已经定义了构造函数,编译器不会再自动生成,即使类中没有显示定义无参构造
//默认构造:只能存在一个
//1.编译器默认生成
//2.显式定义的无参构造
//3.全缺省构造函数
//全缺省默认构造
Date(int y=2020, int m=5, int d=20)
{
_year = y;
_month = m;
_day = d;
}
//重载的构造函数
Date(float f)
{
}
void Display()
{
cout << this->_year << "-" << this->_month << "-" << this->_day << endl;
//this = nullptr;
this->_year = 2022;
}
void SetDate(int year, int month, int day)
{
_year = year;
_month = month;
_day = day;
}
void fun1()
{
cout << "Date::fun1()" << endl;
}
private:
int _year;
int _month;
int _day;
//如果类中存在自定义成员,则构造函数会自动调用自定义成员的默认构造,完成自定义成员的初始化
//如果自定义成员没有默认构造函数,
AA _aa;
};
void test6()
{
Date d;
d.SetDate(2010, 5, 15);
d.Display();
Date d2(2020, 5, 20);
d2.Display();
Date d3();//声明一个函数,不会调用无参构造
}
int main()
{
Date d1, d2;
d1.SetDate(2018, 5, 1);
d2.SetDate(2018, 7, 1);
d1.Display();
d2.Display();
Date* pd1 = &d1;
pd1->Display();
pd1 = nullptr;
//this在不做解引用的场景下,可以为空
//pd1->Display();this指针空,解引用异常
pd1->fun1();//this指针为空,但是this没有进行解引用,程序正常执行
//fun1(pd1);
//pd1->_day=1;
return 0;
}