C++中怎么向函数传递对象
1、传值
C++中可以使用传值的方式向函数传递对象,也就是把对象的值复制一份传递给函数,函数操作的是这个复制的值,而不是原有的对象,因此不会影响到原有的对象。代码如下:
#include <iostream>
using namespace std;
class A {
public:
int a;
A(int a) {
this->a = a;
}
};
void func(A a) {
cout << a.a << endl;
}
int main() {
A a(10);
func(a);
return 0;
}
2、传引用
C++中也可以使用传引用的方式向函数传递对象,函数操作的是原有的对象,因此会影响到原有的对象,其代码如下:
#include <iostream>
using namespace std;
class A {
public:
int a;
A(int a) {
this->a = a;
}
};
void func(A &a) {
a.a = 20;
cout << a.a << endl;
}
int main() {
A a(10);
func(a);
cout << a.a << endl;
return 0;
}
3、传指针
C++中还可以使用传指针的方式向函数传递对象,函数操作的是原有的对象,因此会影响到原有的对象,其代码如下:
#include <iostream>
using namespace std;
class A {
public:
int a;
A(int a) {
this->a = a;
}
};
void func(A *a) {
a->a = 20;
cout << a->a << endl;
}
int main() {
A a(10);
func(&a);
cout << a.a << endl;
return 0;
}
C++中可以使用传值、传引用和传指针的方式向函数传递对象,具体使用哪种方式,要根据实际情况来确定。
上一篇
工作中能用到的git命令有哪些 下一篇
sed和gawk编辑器怎么用 猜您想看
-
Windows下开发linux程序中Source Insight3.5破解方法
一、Sourc...
2023年05月23日 -
Springboot中如何整合Servlet
整合Servl...
2023年07月23日 -
Unity使用C++作为游戏逻辑脚本分析
Unity是一...
2023年07月23日 -
如何使用微信扫码支付?
如何使用微信扫...
2023年04月15日 -
怎样解决Consider renaming one of the beans or enabling overriding by setting spring问题
解决Sprin...
2023年05月25日 -
sparklines的Variance有什么用
什么是spar...
2023年05月22日