C++默认参数 - 声明

Nor*_* Me 1 c++ default-arguments

我在班上创建了一个函数.我将所有声明放在头文件中,并将所有定义放在我的.cpp中.

在我的标题中:

class FileReader{

public:
FileReader(const char*);                        //Constructor
std::string trim(std::string string_to_trim, const char trim_char = '=');

};
Run Code Online (Sandbox Code Playgroud)

在我的.cpp中:

std::string FileReader::trim(std::string string_to_trim, const char trim_char = '='){

std::string _return;
for(unsigned int i = 0;i < string_to_trim.length();i++){
    if(string_to_trim[i] == trim_char)
        continue;
    else
        _return += string_to_trim[i];
}

       return _return;
}
Run Code Online (Sandbox Code Playgroud)

每当我尝试编译并运行它时,我都会遇到两个错误.

错误:为'std :: string FileReader :: trim(std :: string,char)'[-fpermissive]的参数2给出的默认参数

错误:在'std :: string FileReader :: trim(std :: string,char)'[-fpermissive]中的先前规范之后

我究竟做错了什么?我只是希望我的函数有这个默认参数.

And*_*owl 14

你不应该指定默认的参数在函数声明和函数定义.我建议你只把它放在声明中.例如:

class FileReader{
public:
    FileReader(const char*);                        
    std::string trim(std::string string_to_trim, const char trim_char = '=');
    //                                                                ^^^^^
    //                                                     Here you have it
};

std::string FileReader::trim(std::string string_to_trim, const char trim_char)
//                                                                  ^^^^^^^^^
//                                              So here you shouldn't have it
{
    // ....
}
Run Code Online (Sandbox Code Playgroud)

如果函数定义和函数声明对于编译器从进行函数调用的位置都是可见的,那么您还可以选择仅在函数定义中指定默认参数,这也可以.

但是,如果只有函数的声明对编译器可见,那么您必须仅在函数声明中指定默认参数,并从函数定义中删除它们.

  • @CGuy:查看我的回答更新.如果从仅显示声明的点调用该函数,则必须仅将默认参数放在声明中. (2认同)

Alo*_*lon 6

在cpp内部,您不需要默认参数,仅在h文件中