当我们传递一个类的对象作为值时,复制构造函数调用。它将处于连续循环中。但它在字符串的情况下是如何工作的。
例如:
#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一个字符串对象,在函数定义中,我们作为值来处理。
请消除疑虑。
发布于 2018-02-23 20:10:38
复制构造函数不接受原始对象的值,否则会导致无限递归,正如您所说的。实际上,所有复制构造函数都通过引用来获取原始对象的。他们的签名是
T::T(const T&);通过这种方式,复制构造函数可以访问原始对象(而不是副本)作为常量引用,因此它可以执行必要的“复制”操作。
发布于 2018-02-23 21:34:31
通过值传递和通过引用传递之间的基本区别是:
<>F213
此规则适用于基本类型(如int、float、double),也适用于自定义类型(如class objects、std::string等)。
https://stackoverflow.com/questions/48947348
复制相似问题