【问题标题】:C++ Default Arguments - Declaration [closed]C++ 默认参数 - 声明 [关闭]
【发布时间】:2013-03-23 20:34:15
【问题描述】:

我在课堂上创建了一个函数。我将所有声明放在头文件中,将所有定义放在 .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 给出的默认参数 [-fpermissive]

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

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

【问题讨论】:

  • 只做一次就是错误所说的。
  • 错误消息说在“之前的规范之后”指定默认参数是一个“错误”。这意味着什么?

标签: c++ default-arguments


【解决方案1】:

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

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

如果函数定义和函数声明在函数调用的位置对编译器都是可见的,您还可以选择仅在函数定义中指定默认参数 em>,这样也行。

但是,如果只有函数的声明对编译器可见,那么您将不得不在函数声明中指定默认参数,并删除它们来自函数定义。

【讨论】:

  • 嗯,谢谢,工作。我删除了定义中的默认参数。
  • @CGuy:这很奇怪。你用的是什么编译器?它可以工作here
  • @AndyProwl gnu c++ 编译器
  • @CGuy:查看我的答案的更新。如果您从只有声明可见的位置调用函数,则必须仅将默认参数放在声明中。
【解决方案2】:

cpp里面不需要默认参数,只需要在h文件中

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-04
    • 2012-03-22
    • 2020-09-04
    • 2016-07-03
    • 1970-01-01
    • 2010-09-16
    • 1970-01-01
    • 2014-07-05
    相关资源
    最近更新 更多