类和对象Ⅸ---向函数传递对象

1 对象作为函数参数

#include<iostream>

using namespace std;

class Point {
	
	int x, y;
	
	public:
		
		//构造函数 
		Point(int a, int b) {
			
			x = a;
			y = b;
		}
		
		//拷贝构造函数 
		Point (const Point &p) {
			
			x = p.x;
			y = p.y;
			cout<<"Copy Constructing"<<endl;
		}
		
		//成员函数
		//用来修改成员数据的值 
		void set (int a, int b) {
			
			x = a;
			y = b;
		}
		
		void show() {
			
			cout<<"("<<x<<","<<y<<")"<<endl;
		}
};

//对象作为函数参数,调用拷贝构造函数 
void fun(Point point) { //该行语句相当于 Point point = p 
			
			point.set(10, 10);
			cout<<"point's x and y are :"<<endl;
			point.show();
}
//当fun函数结束,point生命周期结束
//之后调用析构函数,用来释放空间 

int main () {
	 
	Point p(1, 1);//该行语句修改Point,与p无关 
	fun(p);
	cout<<"But, p is unchange in main ;"<<endl;
	p.show();
	
	return 0;
} 

执行结果:

 2 指针作为函数参数

#include<iostream>

using namespace std;

class Point {
	
	int x, y;
	
	public:
		
		//构造函数 
		Point(int a, int b) {
			
			x = a;
			y = b;
		}
		
		//拷贝构造函数 
		Point (const Point &p) {
			
			x = p.x;
			y = p.y;
			cout<<"Copy Constructing"<<endl;
		}
		
		//成员函数
		//用来修改成员数据的值 
		void set (int a, int b) {
			
			x = a;
			y = b;
		}
		
		void show() {
			
			cout<<"("<<x<<","<<y<<")"<<endl;
		}
};

//对象作为函数参数,调用拷贝构造函数 
void fun(Point *point) {//该语句相当于Point *point = &p; 

			point->set(10, 10);//等价于 p.set(10, 10); 
			cout<<"point's x and y are :"<<endl;
			point->show();
}
//当fun函数结束,point生命周期结束
//之后调用析构函数,用来释放空间 

int main () {
	 
	Point p(1, 1);//该行语句修改Point,与p无关 
	fun(&p);
	cout<<"But, p is change in main ;"<<endl;
	p.show();
	
	return 0;
} 

执行结果:

3 引用作为函数参数

#include<iostream>

using namespace std;

class Point {
	
	int x, y;
	
	public:
		
		//构造函数 
		Point(int a, int b) {
			
			x = a;
			y = b;
		}
		
		//拷贝构造函数 
		Point (const Point &p) {
			
			x = p.x;
			y = p.y;
			cout<<"Copy Constructing"<<endl;
		}
		
		//成员函数
		//用来修改成员数据的值 
		void set (int a, int b) {
			
			x = a;
			y = b;
		}
		
		void show() {
			
			cout<<"("<<x<<","<<y<<")"<<endl;
		}
};

//对象作为函数参数,调用拷贝构造函数 
//引用相当于别名 
void fun(Point &point) {//该语句相当于Point &point = p; 

			point.set(10, 10); 
			cout<<"point's x and y are :"<<endl;
			point.show();
}
//当fun函数结束,point生命周期结束
//之后调用析构函数,用来释放空间 

int main () {
	 
	Point p(1, 1);//该行语句修改Point,与p无关 
	fun(p);
	cout<<"But, p is change in main ;"<<endl;
	p.show();
	
	return 0;
} 

 执行结果:

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值