C++中的一个小问题
最近在重新开始学习c++,昨天在写代码的过程中发现,在c++中使用值传递和引用传递的一个区别。一般来说,使用值传递是将自定义类型的值传传入函数内部,此时会复制出一份新的对象,而在复制这个新的对象的过程中,会隐式地调用拷贝构造函数。
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32#include<iostream> #include<string> using namespace std; class Person { public: //构造函数 Person(string name) { this->name = name; } //拷贝构造函数 Person(const Person& p) { cout << "使用值传递会隐式地调用拷贝构造函数" << endl; this->name = p.name; } string name; }; //在这里使用值传递 void test01(Person p) { cout << p.name << endl; } int main() { Person p1("tom"); test01(p1); system("pause"); return 0; }
测试结果如下:
最后
以上就是平常夏天最近收集整理的关于C++值传递需要注意的问题的全部内容,更多相关C++值传递需要注意内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复