将临时对象传递给接受指针的函数 [英] Pass temporary object to function that takes pointer
本文介绍了将临时对象传递给接受指针的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试过下面的代码:
#include<iostream>
#include<string>
using namespace std;
string f1(string s)
{
return s="f1 called";
}
void f2(string *s)
{
cout<<*s<<endl;
}
int main()
{
string str;
f2(&f1(str));
}
但此代码不编译。
我认为是:f1返回值,所以它创建临时,其中我采取地址和传递到f2。
现在请解释我在哪里我错了?
But this code doesn't compile.
What I think is : f1 returns by value so it creates temporary, of which I am taking address and passing to f2.
Now Please explain me where I am thinking wrong?
推荐答案
一元&
)。函数 f1()
不返回一个左值,它返回一个右值(对于返回值的函数,除非它返回一个引用,它的返回值是一个右值)因此不能应用一元&
。
The unary &
takes an lvalue (or a function name). Function f1()
doesn't return an lvalue, it returns an rvalue (for a function that returns something, unless it returns a reference, its return value is an rvalue), so the unary &
can't be applied to it.
这篇关于将临时对象传递给接受指针的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文