教师讲解
this指针用途1展示:区分成员和非成员
#include<iostream>
using namespace std;
class Date {
private:
//数据成员
int year, month, day;
public:
//构造函数
Date (int y = 2009, int n = 1, int d = 1) {
year = y;
month = n;
day = d;
}
/*
c++为类的每个成员函数的形参表中添加*this
类似于这样
void show(const Date *this = &d1) {
cout<<this.year<<"."<<this.month<<"."<<this.day<<endl;
}
*/
//成员函数show
void show() {
cout<<year<<"."<<month<<"."<<day<<endl;
}
};
/*
*this的作用
1 通过this区分成员和非成员
2 类的方法需要返回当前对象的引用
*/
int main () {
//两个对象,d1,d2
//调用带3个整形参数的构造函数
Date d1(1993,3,20),d2(2000,1,2);
d1.show();
//查看整形占用的字节数
cout<<sizeof(int)<<endl;
cout<<sizeof(Date)<<endl;
return 0;
}
执行结果:
#include<iostream>
using namespace std;
class Date {
private:
//数据成员
int year, month, day;
public:
//构造函数
Date (int year = 2009, int month = 1, int day = 1) {
this->year = year;
this->month = month;
this->day = day;
}
/*
c++为类的每个成员函数的形参表中添加*this
类似于这样
void show(const Date *this = &d1) {
cout<<this.year<<"."<<this.month<<"."<<this.day<<endl;
}
*/
//成员函数show
void show() {
cout<<year<<"."<<month<<"."<<day<<endl;
}
};
/*
*this的作用
1 通过this区分成员和非成员
2 类的方法需要返回当前对象的引用
*/
int main () {
//两个对象,d1,d2
//调用带3个整形参数的构造函数
Date d1(1993,3,20),d2(2000,1,2);
d1.show();
//查看整形占用的字节数
cout<<sizeof(int)<<endl;
cout<<sizeof(Date)<<endl;
return 0;
}
执行结果:
以下代码代码展示用途2:返回当前对象的引用
#include<iostream>
using namespace std;
class Date {
private:
//数据成员
int year, month, day;
public:
//构造函数
Date (int year = 2009, int month = 1, int day = 1) {
this->year = year;
this->month = month;
this->day = day;
}
/*
c++为类的每个成员函数的形参表中添加*this
类似于这样
void show(const Date *this = &d1) {
cout<<this.year<<"."<<this.month<<"."<<this.day<<endl;
}
*/
//成员函数show
void show() {
cout<<year<<"."<<month<<"."<<day<<endl;
}
//成员函数fun
//const *this = &d1 ;
Date &fun() {
//不能return d1,成员函数不认识d1
return *this;
}
};
/*
*this的作用
1 通过this区分成员和非成员
2 类的方法需要返回当前对象的引用
*/
int main () {
//两个对象,d1,d2
//调用带3个整形参数的构造函数
Date d1(1993,3,20),d2(2000,1,2);
d1.show();
//查看整形占用的字节数
//cout<<sizeof(int)<<endl;
//cout<<sizeof(Date)<<endl;
//该语句的结果就指d1;
(d1.fun()).show();
return 0;
}
执行结果: