一.使用对象作为函数参数
假设移动前的坐标为,(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