C++ c++;:函数不能重载

C++ c++;:函数不能重载,c++,c++11,C++,C++11,我遇到以下输出的编译时错误: $ 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::fileEx

我遇到以下输出的编译时错误:

$ 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
{
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();
    }
};
(您甚至将声明保密,并将定义公开。)


删除声明或将定义移到类定义之外(我建议使用后者)。

因为方法已经声明,所以必须在类声明之外定义它:

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