相关疑难解决方法(0)

将临时对象传递给带指针的函数

我试过以下代码:

#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));
}
Run Code Online (Sandbox Code Playgroud)

但是这段代码没有编译.
我的想法是:f1按值返回所以它创建临时,我正在接收地址并传递给f2.
现在请解释一下我在想错的地方?

c++ function temporary

6
推荐指数
2
解决办法
6370
查看次数

如何使用指针的统一初始化?

例如,我有一个班级

struct A
{
    A(int i, double d) {...}
};
Run Code Online (Sandbox Code Playgroud)

和带参数A的函数

void f(A a);
Run Code Online (Sandbox Code Playgroud)

我可以通过调用函数

f( { 1, 3.14 } );
Run Code Online (Sandbox Code Playgroud)

如果函数有参数A*

void g(A* a);
Run Code Online (Sandbox Code Playgroud)

怎么叫它像

g( my_new{1, 3.14} ); // Note: no type A is shown here.
Run Code Online (Sandbox Code Playgroud)

或者如何在这里推导出类型A?

c++ initialization

3
推荐指数
1
解决办法
420
查看次数

标签 统计

c++ ×2

function ×1

initialization ×1

temporary ×1