通过引用传递给构造函数 [英] Passing by reference to a constructor
问题描述
我决定看看给成员分配引用是否会使成员成为引用。我编写了以下代码片段进行测试。有一个简单的类 Wrapper
,其中一个 std :: string
作为成员变量。我在构造函数中使用 const string&
并将其分配给public成员变量。稍后在 main()
方法中,我修改了成员变量,但是我传递给构造函数的 string
保持不变,如何来?我认为在Java中变量会更改,为什么不在此代码段中?
I decided to see if assigning a reference to a member would make a member a reference. I wrote the following snippet to test it. There's a simple class Wrapper
with an std::string
as a member variable. I take take a const string&
in the constructor and assign it to the public member variable. Later in the main()
method I modify the member variable but the string
I passed to the constructor remains unchanged, how come? I think in Java the variable would have changed, why not in this code snippet? How exactly do references work in this case?
#include <iostream>
#include <string>
using namespace std;
class Wrapper
{
public:
string str;
Wrapper(const string& newStr)
{
str = newStr;
}
};
int main (int argc, char * const argv[])
{
string str = "hello";
cout << str << endl;
Wrapper wrapper(str);
wrapper.str[0] = 'j'; // should change 'hello' to 'jello'
cout << str << endl;
}
推荐答案
在构造函数,您需要有一个引用成员
To assign a reference in a constructor you need to have a reference member
class A{
std::string& str;
public:
A(std::string& str_)
: str(str_) {}
};
str现在是对您传入的值的引用。const refs同样适用
str is now a reference to the value you passed in. Same applies for const refs
class A{
const std::string& str;
public:
A(const std::string& str_)
: str(str_) {}
};
但是,请记住,一旦分配了引用,就无法更改,因此如果需要分配更改str则必须改为使用指针。
However don't forget that once a reference has been assigned it can not be changed so if assignment requires a change to str then it will have to be a pointer instead.
这篇关于通过引用传递给构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!