[英]Passing by reference to a constructor
我决定查看是否为成员分配引用会使成员成为引用。 我编写了以下代码片段来测试它。 有一个简单的类Wrapper
,其中std::string
作为成员变量。 我在构造const 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;
}
要在构造函数中指定引用,您需要具有引用成员
class A{
std::string& str;
public:
A(std::string& str_)
: str(str_) {}
};
str现在是对传入的值的引用。同样适用于const引用
class A{
const std::string& str;
public:
A(const std::string& str_)
: str(str_) {}
};
但是不要忘记,一旦分配了引用,它就无法更改,因此如果赋值需要更改为str,那么它必须是指针。
因为Wrapper::str
不是引用,所以它是一个独立的对象。 所以当你执行str = newStr
,你正在复制字符串。
class Wrapper
{
public:
string& str;
Wrapper(string& newStr) : str(newStr) {}
};
注意,你不能接受一个const string&
并将它存储在一个string&
,这样做会失去const-correctness。
您需要使用初始化程序并将str
声明为引用,如下所示:
class Wrapper {
public:
string &str;
Wrapper(string& newStr)
: str(newStr) {
}
};
你编写它的方式,你所做的就是复制传递给构造函数的引用的值。 你没有保存参考。 通过将引用声明为类成员并使用对另一个字符串实例的引用对其进行初始化,您将获得您正在寻找的行为。
你的主体变量是std::string
。
你的参数变量是const std::string&
。
引用中的const始终是“低级别const”,这意味着它修改了对象的类型而不是实际对象。
相比之下,“顶级const”修改了一个实际的对象。 阅读顶级const上的C ++ Primer以获得澄清。
传递参数时,您的任务如下所示:
const std::string& = std::str; //Values are ommited
// i.e const std::string newStr = std::string str
您正在使用可接受的non-const value
初始化const type reference
。 您不应该使用该引用更改std::string str
的值。 并且,如果您尝试在构造函数中更改newStr
的值,您将收到编译错误 。
接下来,你在构造函数中做了另一个赋值,这也是可以接受的:
std::string = const std::string
这一事实wrap.str[0]
不改变str
的main
是,虽然参考了用于实例化class str
, class str
有它自己的对象和未链接到main str
。 在参数中使用该引用只是将该参数链接到main str
; 不是main str
class str
。
如果引用了类变量,那么它可能已经改变了。
您应该将Wrapper::str
声明为string&
而不是string
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.