当我们将一个类的对象作为值传递给复制构造函数调用时。它将处于连续循环中。但是它在字符串的情况下如何工作。
例如:
#include <iostream>
#include <string>
using namespace std;
string read_string(std::string s)
{
std::string test;
cout<<s;
test=s;
return test;
}
int main()
{
string sir = "start";
cout << "SIR starts out as : '" << sir << "'" << endl;
sir = read_string(sir);
cout << "and becomes '" << sir << "', after return from function." << endl << endl;
return 0;
}
这里 read_string(sir)
,我们向 sir 传递一个字符串对象,在函数定义中我们将其作为值处理。
请解惑
最佳答案
复制构造函数不会按值获取原始对象,否则会导致无限递归,如您所说。事实上,所有复制构造函数都通过引用获取原始对象。他们的签名是
T::T(const T&);
通过这种方式,复制构造函数可以访问作为常量引用的原始对象(而不是拷贝),因此它可以执行必要的“复制”操作。
关于c++ - 关于字符串变量按值传递的说明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48947348/