c++默认参数-声明

C++ Default Arguments - Declaration

本文关键字:-声明 参数 默认 c++      更新时间:2023-10-16

我在我的类中创建了一个函数。我把所有的声明放在头文件中,所有的定义放在。cpp中。

在我的header:

class FileReader{
 
public:
FileReader(const char*);                        //Constructor
std::string trim(std::string string_to_trim, const char trim_char = '=');
};
In my .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;
}

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

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

error: after previous specification in 'std::string FileReader::trim(std::string, char)' [-fpermissive]

我做错了什么?我只是想让我的函数有这个默认参数

不应该在函数声明和函数定义中同时指定默认实参。我建议您只将放在声明中。例如:

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
{
    // ....
}

如果函数定义和函数声明在函数调用时对编译器都是可见的,您还可以选择在函数定义中只指定默认参数,这也可以。

然而,如果编译器只看到函数的声明,那么你就必须在函数声明中只指定默认参数,并从函数定义中删除它们。

在CPP内部不需要默认参数,只在h文件