c++默认参数-声明
C++ Default Arguments - Declaration
我在我的类中创建了一个函数。我把所有的声明放在头文件中,所有的定义放在。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文件
相关文章:
- 在C++中声明一个函数时,它需要有函数本身的参数吗
- 对可变参数使用声明.如何选择正确的功能
- Arduino C++在构造函数中用参数声明对象数组
- 标准::向量声明中使用的模板参数
- 当简单捕获中的标识符显示为参数的声明符 ID 时,没有编译器诊断
- 将类型声明为类型模板参数的模板参数的一部分是否合法?
- 构造函数/函数声明参数列表中的统一初始化
- C++ - 声明指向返回任何类型并获取任意数量参数的函数的指针
- 带参数的数据结构的全局声明
- C++使用默认模板参数键入别名和转发声明
- 警告:忽略模板参数上的属性..在 std::unique_ptr (-wignore 属性)的声明中
- C++声明模板参数阴影模板参数错误
- "extern"声明以及带有和不带参数列表的类模板实例的后续定义
- 如何使用参数声明实例?
- 采用nulltpr_t的构造函数:函数定义不声明参数
- c++ 函数定义不声明参数
- 在循环范围之外声明参数是否更有效?
- 在linux下使用mingw交叉编译器声明"参数"中的两种或多种数据类型
- Clang Format多行函数声明参数问题
- 氧-声明参数为可选的