C++ 我应该如何处理c++;?

C++ 我应该如何处理c++;?,c++,string,arguments,C++,String,Arguments,假设我想写一个这样的函数: int get_some_int(string index) { ...perform magic... return result; } int var = obj.get_some_int("blah"); 但是,我也希望能够这样称呼它: int get_some_int(string index) { ...perform magic... return result; } int var = obj.get_some_in

假设我想写一个这样的函数:

int get_some_int(string index) {
    ...perform magic...
    return result;
}
int var = obj.get_some_int("blah");
但是,我也希望能够这样称呼它:

int get_some_int(string index) {
    ...perform magic...
    return result;
}
int var = obj.get_some_int("blah");
但是,我不能这样做,因为
constchar[4]
不是
conststring&

我可以做到:

int get_some_int(char* index) {
    ...perform magic...
    return result;
}
但是,这发出了很多警告,暗示这不是应该怎么做的

那么,处理字符串参数的正确方法是什么

我不能这样做,因为常量字符[4]不是常量字符串&

不,但是
std::string
有一个非
显式的
转换构造函数,因此创建了一个临时的
std::string
,因此您处于清除状态。-

我不能这样做,因为常量字符[4]不是常量字符串&

不,但是
std::string
有一个非
显式的
转换构造函数,因此创建了一个临时的
std::string
,因此您处于清除状态。-

做一个:

int var=obj.get_some_int(字符串(“blah”)

如果你觉得更舒服的话。

做一个:

int var=obj.get_some_int(字符串(“blah”)


如果你觉得它更舒服。

它应该像你做的那样工作

int get_some_int(string index) {  // This works as std::string has a constructor
                                  // That takes care of the conversion
                                  // from `char const*`  which you char[4] 
                                  //decays into when passed to a function
但更好的解决方案是使用常量引用:

int get_some_int(string const& index) {  // works for the same reasson

这里使用const表示函数应该如何工作,并传递有关如何使用输入的信息。同样,当与返回字符串常量引用的方法(比如从常量对象)一起使用时,它仍将按预期工作。

它应该像您所做的那样工作

int get_some_int(string index) {  // This works as std::string has a constructor
                                  // That takes care of the conversion
                                  // from `char const*`  which you char[4] 
                                  //decays into when passed to a function
但更好的解决方案是使用常量引用:

int get_some_int(string const& index) {  // works for the same reasson

这里使用const表示函数应该如何工作,并传递有关如何使用输入的信息。同样,当与返回对字符串的常量引用的方法一起使用时(比如从常量对象),它仍将按预期工作。

如果
std::is__same::value
(我假设这是真的,因为我假设您使用
使用命名空间std
,您不应该这样做)。您可能同时使用
以及定义自己的类型
string
,因此它不起作用。我敢打赌其中一个警告是告诉您使用
const
。如果
std::is__::value
(我假设这是真的,因为我假设您使用
名称空间std
,您不应该这样做)。您可能同时使用
,并且定义了自己的类型
string
,因此它不起作用。我敢打赌,其中一个警告是告诉您使用
const
。@您确定吗。通常这将是函数内部的临时属性(如果您正在构建真正的索引)。但如果是,则使用初始值版本。@是否确定。通常这将是函数内部的临时版本(如果您正在构建实际索引)。如果是,则使用初始值版本。