通过引用传递给构造函数

rcp*_*lus 26 c++ constructor pass-by-reference

我决定查看是否为成员分配引用会使成员成为引用.我编写了以下代码片段来测试它.有一个Wrapper带有std::string成员变量的简单类.我const string&在构造函数中取一个并将其分配给public成员变量.后来在main()方法中我修改了成员变量但是string我传给构造函数的方法保持不变,怎么样?我认为在Java中变量会发生变化,为什么不在这段代码中呢?在这种情况下,引用究竟是如何工作的?

#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;
}
Run Code Online (Sandbox Code Playgroud)

111*_*111 33

要在构造函数中指定引用,您需要具有引用成员

 class A{
     std::string& str;
 public:
     A(std::string& str_)
     :    str(str_) {} 
 };
Run Code Online (Sandbox Code Playgroud)

str现在是对传入的值的引用.同样适用于const引用

 class A{
     const std::string& str;
 public:
     A(const std::string& str_)
     :    str(str_) {} 
 };
Run Code Online (Sandbox Code Playgroud)

但是不要忘记,一旦分配了引用,它就无法更改,因此如果赋值需要更改为str,那么它必须是指针.

  • 有趣的是,要避免将引用作为数据成员:https://herbsutter.com/2020/02/23/references-simply/ (2认同)

Oli*_*rth 8

因为Wrapper::str它不是引用,所以它是一个独立的对象.所以,当你这样做时str = newStr,你正在复制字符串.


and*_*and 5

您需要使用初始值设定项并声明str为引用,如下所示:

class Wrapper {
public:
   string &str;

   Wrapper(string& newStr)
      : str(newStr) {
   }
};
Run Code Online (Sandbox Code Playgroud)

按照您编写的方式,您所做的就是复制传递给构造函数的引用的值。您没有保存参考。通过将引用声明为类成员并使用对另一个字符串实例的引用来初始化它,您将获得您正在寻找的行为。


net*_*der 5

class Wrapper
{
public:
   string& str;

   Wrapper(string& newStr) : str(newStr) {}
};
Run Code Online (Sandbox Code Playgroud)

注意,你不能接受const string&并将其存储在a中string&,这样做会失去const-correctness.