Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 失去';常数';修饰语_C++ - Fatal编程技术网

C++ 失去';常数';修饰语

C++ 失去';常数';修饰语,c++,C++,可能重复: 请查看以下代码: typedef wstring& RT; RT Change(const RT v) { v += L"234"; // why can I change this argument??? return v; } int _tmain(int argc, _TCHAR* argv[]) { wstring str = L"111"; wstring &str2 = Change(str); re

可能重复:

请查看以下代码:

typedef wstring& RT;
RT Change(const RT v)
{
    v += L"234"; // why can I change this argument???

    return v;
}

int _tmain(int argc, _TCHAR* argv[])
{    
    wstring str = L"111";
    wstring &str2 = Change(str);

    return 0;
}
我很惊讶“Change”函数中的参数“v”可以更改。我们失去了“const”修饰语。诸如std::add_const之类的元函数没有帮助,您能解释一下这种行为吗


工具:VS2010

它有点像表达式中的优先级。当你说

const wstring & foo;
它使foo成为对常量wstring的引用。你可以这样想:

(const wstring) & foo;
在创建typedef时,实际上更改了优先级

const RT foo;
const wstring & foo;  // not equivalent, RT is a typedef, not a macro
const (wstring &) foo;  // this is effectively what happens
常量生成foo常量,而不是foo引用的内容


当然,正如FredOverflow所指出的,const引用是多余的,因为您不能将其分配给引用,而只能分配给它所引用的对象。因此,结果是foo只是一个普通的旧引用。

它有点像表达式中的优先级。当你说

const wstring & foo;
它使foo成为对常量wstring的引用。你可以这样想:

(const wstring) & foo;
在创建typedef时,实际上更改了优先级

const RT foo;
const wstring & foo;  // not equivalent, RT is a typedef, not a macro
const (wstring &) foo;  // this is effectively what happens
常量生成foo常量,而不是foo引用的内容


当然,正如FredOverflow所指出的,const引用是多余的,因为您不能将其分配给引用,而只能分配给它所引用的对象。因此,结果是foo只是一个普通的旧引用。

我很确定最后一行忽略了
const
,因为没有
const
引用。我很确定最后一行忽略了
const
,因为没有所谓的
const
reference,我不同意“完全重复”。答案基本上是一样的,但另一个问题意味着当模板归结为typedefing时,它就是问题的一部分。出于这个原因,这个问题的版本可能会为人们搜索提供更多的好处。我不同意“完全重复”的说法。答案基本上是一样的,但另一个问题意味着当模板归结为typedefing时,它就是问题的一部分。出于这个原因,这个问题的版本可能会为人们搜索提供更多的好处。