2

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

在我的标题中:

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

};

在我的.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;
}

每当我尝试编译和运行它时,都会出现两个错误。

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

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

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

4

2 回答 2

15

You should not specify the default argument both in the function declaration and in the function definition. I suggest you putting it in the declaration only. For instance:

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

In case both the function definition and the function declaration are visible to the compiler from the point where the function call is being made, you would also have the option of specifying the default arguments in the function definition only, and that would work as well.

However, if only the declaration of the function is visible to the compiler, then you will have to specify the default argument in the function declaration only, and remove them from the function definition.

于 2013-03-23T20:35:42.090 回答
9

inside the cpp you don't need the default parameter , only in the h file

于 2013-03-23T20:36:25.763 回答