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编辑器怎么用 猜您想看
-
如何在 EmBlog 博客系统中设置阅读次数统计
:如何在 Em...
2023年04月15日 -
python如何实现输入一行字符分别统计出其中英文字母、空格、数字和其它字符的个数
问题描述给定一...
2023年07月21日 -
Windows XP 如何进行磁盘分区和格式化
如何进行磁盘分...
2023年04月15日 -
如何在Edge浏览器中配置“下载”
在Micros...
2023年05月13日 -
C++名称该怎么写
C++是一种广...
2023年07月23日 -
Python中pandas数据分析库如何实现数据可视化
1、Panda...
2023年05月26日