【C++】函数参数的传递机制。以中国象棋“马“的移动为例。

本文通过中国象棋中‘马’的移动规则,探讨了C++中函数参数的传递机制,包括使用对象、对象指针和引用的方式。实例展示在不同方式下,对象坐标如何在函数调用前后发生变化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一.使用对象作为函数参数
假设移动前的坐标为,(x0,y0)移动->(x0+1,y0+2)

#include<iostream>
#include<iomanip>
using namespace std;
class point{
	private:
		int x,y;
		public:
			point(int x1,int y1);
			void move(point p);
			void print();
};
int main()
{
	point p1(1,2);
	cout<<"移动前:"; 
	p1.print();
	cout<<"移动后:";
	p1.move(p1); 
	p1.print();
	return 0;
	
}
point::point(int x1,int y1)
{
	x=x1;
	y=y1;
}
void point::print()
{
	cout<<"x="<<x<<setw(3)<<"y="<<y<<endl;
}
void point::move(point p)
{
	p.x=p.x+1;
	p.y=p.y+2;
}

运行结果:
移动前:x=1 y=2
移动后:x=1 y=2


二:使用对象指针作为函数参数

#include<iostream>
#include<iomanip>
using namespace std;
class point{
	private:
		int x,y;
		public:
			point(int x1,int y1);
			void move(point *p);
			void print();
};
int main()
{
	point p1(1,2);
	cout<<"移动前:"; 
	p1.print();
	cout<<"移动后:";
	p1.move(&p1); 
	p1.print();
	return 0;
	
}
point::point(int x1,int y1)
{
	x=x1;
	y=y1;
}
void point::print()
{
	cout<<"x="<<x<<setw(3)<<"y="<<y<<endl;
}
void point::move(point *p)
{
	(*p).x=(*p).x+1;
	(*p).y=(*p).y+2;
}

运行结果:
移动前:x=1 y=2
移动后:x=2 y=4


三:使用引用作为函数参数

#include<iostream>
#include<iomanip>
using namespace std;
class point{
	private:
		int x,y;
		public:
			point(int x1,int y1);
			void move(point &p);
			void print();
};
int main()
{
	point p1(1,2);
	cout<<"移动前:"; 
	p1.print();
	cout<<"移动后:";
	p1.move(p1); 
	p1.print();
	return 0;
	
}
point::point(int x1,int y1)
{
	x=x1;
	y=y1;
}
void point::print()
{
	cout<<"x="<<x<<setw(3)<<"y="<<y<<endl;
}
void point::move(point &p)
{
	p.x=p.x+1;
	p.y=p.y+2;
}

运行结果:
移动前:x=1 y=2
移动后:x=2 y=4


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值