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编辑器怎么用 猜您想看
-
用groovy写的类在spring中无法初始化为bean的原因是什么
1. groo...
2023年05月26日 -
油猴脚本调试技巧:使用 Tampermonkey 的 GM_trace 打印函数调用栈
利用Tampe...
2023年05月13日 -
如何排查服务器的内存泄露
1. 检查内存...
2023年05月26日 -
Solidity语法的重载,继承的定义是什么
Solidit...
2023年05月26日 -
如何理解R语言中的功效分析
什么是功效分析...
2023年07月20日 -
常用的正则表达式速查表
什么是正则表达...
2023年05月25日