函数不能被重载
c++: function cannot be overloaded
我遇到一个编译时错误,输出如下:
$ g++ -ggdb `pkg-config --cflags opencv` -o `basename main.cpp .cpp` main.cpp StringMethods/StringMethods.cpp `pkg-config --libs opencv` -std=c++0x
In file included from main.cpp:2:0:
VideoFile.hpp:32:10: error: ‘bool VideoFile::fileExists(const string&)’ cannot be overloaded
bool fileExists(const std::string & path)
^
VideoFile.hpp:15:10: error: with ‘bool VideoFile::fileExists(const string&)’
bool fileExists(const std::string & path);
然而,我不明白这个错误有什么意义,因为我只有在编写定义时直接复制和粘贴的函数声明。
class VideoFile
{
private:
std::string filePath;
bool fileExists(const std::string & path);
public:
VideoFile(const std::string & path)
:filePath(path)
{
filePath = StringMethods::trim(path);
if (!fileExists(filePath))
throw std::runtime_error("The file: " + filePath + " was not accessible");
}
~VideoFile()
{
}
bool fileExists(const std::string & path)
{
std::ifstream file(path);
return file.good();
}
};
不能在类定义中声明和定义成员函数。
(您甚至将声明设为私有而将定义设为公共)
要么删除声明,要么将定义移到类定义之外(我推荐后者)。
在类本身中有两次fileExists
。一次没有定义
bool fileExists(const std::string & path);
和一次定义
bool fileExists(const std::string & path)
{
std::ifstream file(path);
return file.good();
}
您有两个选项:要么删除无定义部分,要么删除有定义部分并在类外部提供定义。
因为方法已经被声明了,所以必须在类声明之外定义它:
class VideoFile
{
// ...
bool fileExist(const std::string path);
// ...
};
bool VideoFile::fileExist(const std::string& path)
{
// ...
}
你不能重载fileExists函数的另一个具有相同的参数,只是使用不同的作用域,就像你在你的例子。您可以保留已有的两个fileExists函数,但需要使用不同的参数,如下所示
class VideoFile
{
private:
bool fileExists();
public:
bool fileExists(const std::string & path) // overloading bool fileExists();
{
std::ifstream file(path);
return file.good();
}
};
相关文章:
- 为什么我不能在 C++ 中的特定函数重载中调用同一函数的任何其他重载?
- 取消引用运算符不能重载
- 不能将重载比较运算符与 Catch 测试一起使用
- 成员函数不能为集合迭代器和const_iterator的输入重载(但可以为其他 STL 迭代器重载)
- 为什么我不能用两个参数重载 C++ 运算符 []?
- ostream_iterator运算符=在pair<int,int>上失败,但在包装器类上工作。我不能为成对<>重载运算符<<吗?
- 派生类不能用另一个基类的成员重载基类中的私有成员
- 为什么我不能重载运算符<< 与 ostream 和 map( 或 unordered_map)?
- 不能在友元函数中使用重载运算符
- 为什么我不能重载我传递给 std::upper_bound 的比较器
- 不允许使用类型名称,(不能使用重载)
- 在 c++ 中,为什么我们可以重载"运算符 ->"而不能重载"运算符"。
- 不能为我自己的类重载运算符<<
- 不能只删除方法的常量重载?
- 为什么 decltype 不能使用重载函数?
- 不能重载 = 使对象 1 = 0;
- 运算符重载:不能添加两个指针
- 为什么操作符重载不能正常执行
- std::set的操作符重载不能正常工作
- 为什么运算符重载不能正常工作