我决定测试将引用分配给成员是否会使成员成为引用。我编写了以下片段进行测试。有一个简单的类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;
}