C++ 非常量引用的初始化

C++ 非常量引用的初始化,c++,reference,initialization,C++,Reference,Initialization,我想我从TC++PL中学到了这一点 “非常量引用应通过左值初始化” 下面是我的问题 int f1(int &x) { return 1; } int f2() { return 1; } int f3(string &s) { return 1; } string f4() { return "1"; } int main() { cout<<f1(f2())<<endl; // Error. cou

我想我从TC++PL中学到了这一点 “非常量引用应通过左值初始化”

下面是我的问题

int f1(int &x)
{
    return 1;
}

int f2()
{
    return 1;
}

int f3(string &s)
{
    return 1;
}

string f4()
{
    return "1";
}

int main()
{
    cout<<f1(f2())<<endl; // Error.
    cout<<f3(f4())<<endl; // OK.
}
intf1(int&x)
{
返回1;
}
int f2()
{
返回1;
}
int f3(字符串和s)
{
返回1;
}
字符串f4()
{
返回“1”;
}
int main()
{

cout这两个语句都不起作用。原因是f(2)返回一个常量,而f(1)期望一个非常量,因此会出现错误消息

int f3(const string &s)
{
   return 1;
}

int f1(const int &x)
{
   return 1;
}

这将消除错误。

< P>我认为,你使用微软Visual C++编译器,默认选项编译这个代码。因为它中有非标准扩展,允许绑定R值值引用。
有关此代码在MSVC中如何工作的详细信息,请阅读

从概念上讲,此代码不应工作。为什么

答:每个函数f1和f3都使用一个参数作为调用地址。因此,它必须能够引用传递给它的参数的地址。因此,对函数f1和f3中参数值的任何更改都会影响传递给它的实际变量

但函数f4和f2的返回值是常量,不能更改。因此,会出现错误

现在,如果只需将函数f2和f4的值传递给函数f1和f3,只需按值传递即可。为此,请删除参数中的&符号。

int\u tmain(int argc,\u TCHAR*argv[])
int _tmain(int argc, _TCHAR* argv[])
{
    cout<<f1(f2())<<endl; 
    int &a(1); //This is what gonna happen when your f2() returns 1 and 1 is passed in    f1(int&). That is invalid.
        cout<<f3(f4())<<endl; 
    // string& str(string("1"));//when "1" is returned from f4() it will be implicitly casted to string("1") and pass in f3 as f3(string("1")). There it comes valid reference.


    return 0;
}
{
coutIt不应该工作。您使用的编译器?不适合我,正如我所期望的。我在VS2010中编译代码。为什么f1将参数作为“按地址调用”?它只是将引用作为parameter@Subhajit如果你注意到这个(int&x),这是一个通过引用/地址进行的调用,这是一个按值调用。现在您可以传递另一个变量或常量值。希望这很清楚“当您的f2()返回1时会发生这种情况”-什么?
f2()
返回prvalue,如何将其强制转换为引用?是的,它不能强制转换为引用,这就是它显示错误的原因。抱歉,这是我的错误。但是您告诉:第二种情况下的“有效引用”是指
string&str(string(“1”);
有效,还是我遗漏了什么(再次>_