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;
}
执行结果: