C++值传递需要注意的问题
C++中的一个小问题
最近在重新开始学习c++,昨天在写代码的过程中发现,在c++中使用值传递和引用传递的一个区别。一般来说,使用值传递是将自定义类型的值传传入函数内部,此时会复制出一份新的对象,而在复制这个新的对象的过程中,会隐式地调用拷贝构造函数。
#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;
}
测试结果如下:
还没有评论,来说两句吧...