Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/xcode/7.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++,我有一个这样的构造函数: class class_foo{ std::string s_; class_foo(std::string& s) : s_(s){}; } void class_foo(std::string& s) : s_(s){}; 我知道我能做到: std::string s = "test"; cf = class_foo(s); 有没有办法做到: cf = class_foo("test"); cf = class_foo("te

我有一个这样的构造函数:

class class_foo{
    std::string s_;
    class_foo(std::string& s) : s_(s){};
}
void class_foo(std::string& s) : s_(s){};
我知道我能做到:

std::string s = "test";
cf = class_foo(s);
有没有办法做到:

cf = class_foo("test");
cf = class_foo("test");
但是它说:
注意:候选构造函数不可行:第三个参数需要一个l值

@埃罗里卡是对的。我可以简单地使用如下常量:

我有一个这样的构造函数:

class class_foo{
    std::string s_;
    class_foo(std::string& s) : s_(s){};
}
void class_foo(std::string& s) : s_(s){};
构造函数不能有返回类型(甚至
void

有没有办法做到:

cf = class_foo("test");
cf = class_foo("test");

如果要将参数保留为非常量引用,则不需要。然而,不清楚为什么您希望它是非常量引用。也许它不需要是一个非常量引用?如果您不打算修改参数,那么应该使用对const的引用。那么你建议的结构就行了。

什么是
s
?可能的重复:好捕获。我更新了。哦,是的,你是对的。我可以声明它是常量