我决定查看是否为成员分配引用会使成员成为引用。我写了下面的代码片段来测试它。有一个简单的类Wrapper
,std::string
作为成员变量。我在构造函数中采取const string&
并将其分配给公共成员变量。后来在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;
}
C++中的类型是你的命令,他们不会神奇地变成别的东西。你说'string',并且你得到一个'string'。如果你想参考,你会说'string&'。 – 2012-02-29 21:38:12
你滥用人们的太简单的问题:) – Mikhail 2012-02-29 21:39:20
在Java中,变量不会改变,因为代码甚至没有编译;不允许修改Java中的字符串。 – 2012-02-29 21:40:16