我可以使用std :: set <std :: string>作为函数的默认参数吗?

Der*_*rek 1 c++

我是新手,现在确定这是否可行.我想为std::set<std::string>函数添加一个参数,并将其默认值设置为NULL,以避免对以前的使用产生影响.

基本上,

func(int a); turns into  
func(int a, std::set<std::string> & temp = NULL);
Run Code Online (Sandbox Code Playgroud)

但这会给我一个错误 "error C2440: 'default argument' : cannot convert from 'int' to 'std::set<_Kty> &'"

有人可以帮我这个吗?

谢谢

Bor*_*lid 5

要将默认值设置为NULL,您必须传递一个值std::set<std::string>*,而不是对值类型的引用.

此外,如果您传递非指针类型并且您想要分配任何默认值,则它必须是const引用,因为您不能(理所当然!)为其分配临时值.

因此,您对"默认"值的选择基本上是:

std::set<std::string>* = NULL
Run Code Online (Sandbox Code Playgroud)

要么:

const std::set<std::string>& = std::set<std::string>()
Run Code Online (Sandbox Code Playgroud)

或选项3,更直接地使用函数重载:

void myfunction() {dothing(0);}
void myfunction(std::set<std::string>& optional_param) 
{ dothing(optional_param.size()); }
Run Code Online (Sandbox Code Playgroud)

或选项4,具有相应的bool指示参数是否"设置":

void myfunction(std::set<std::string>& param, bool param_has_meaning=true) {}
Run Code Online (Sandbox Code Playgroud)

看起来你已经在第三个选项的轨道上了.您只需要编写两个定义,一个定义,一个不带参数.