函数不能被重载

c++: function cannot be overloaded

本文关键字:重载 不能 函数      更新时间:2023-10-16

我遇到一个编译时错误,输出如下:

$ 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();
       }
    };