类和对象Ⅷ----深拷贝与浅拷贝+this指针

教师讲解

深拷贝与浅拷贝

this指针

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;
}

执行结果:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值