How to pass a string type path to boost::filesyste

2019-06-12 07:22发布

问题:

I have the following class using boost filesystem, but encountered the problem when compiling.

/// tfs.h file:

#include <boost/filesystem.hpp>
#include <iostream>
#include <string>

using namespace boost;
using namespace std;

class OSxFS
{
  public:
    OSxFS(string _folderPath)
    {
      mFolderPath(_folderPath);
    }

    string ShowStatus()
    {
      try
      {
        filesystem::file_status folderStatus = filesystem::status(mFolderPath);
        cout<<"Folder status: "<<filesystem::is_directory(folderStatus)<<endl;
      }
      catch(filesystem::filesystem_error &e)
      {
        cerr<<"Error! Message: "<<e.what()<<endl;
      }
    }

  private:
    filesystem::path mFolderPath;
}

In the m.cpp file, I use the following code to invoke the OSxFS class:

///m.cpp file 

#include "tfs.h"
#include <iostream>
#include <string>

using namespace std;
using namespace boost;

int main()
{  
  string p = "~/Desktop/";
  OSxFS folderX(p);
  folderX.ShowStatus();
  cout<<"Thank you!"<<endl;
  return 0;
}

However, I got the error message when I compile them by g++ in xCode:

In file included from m.cpp:1:
tfs.h: In constructor ‘OSxFS::OSxFS(std::string)’:
tfs.h:13: error: no match for call to ‘(boost::filesystem::path) (std::string&)’
m.cpp: At global scope:
m.cpp:5: error: expected unqualified-id before ‘using’

If I implement the function ShowStatus() of class OSxFS in a single main.cpp, it works. So, I guess the problem is about how to pass the string variable _folderPath to the class's constructor?

回答1:

You are missing a semicolon at the end of class OSxFS. Also, you are using the incorrect syntax to call the constructor of path. Try:

OSxFS(string _folderPath) :
    mFolderPath(_folderPath)
{ 
}

mFolderPath(_folderPath); in the body of the OSxFS constructor is attempting to call mFolderPath as a function.



标签: c++ boost g++