0

私は以下のコードを持っています--->

ConfigFile.h

#ifndef __CONFIG_FILE_H__
#define __CONFIG_FILE_H__

#include <string>
#include <map>

const std::string SECTION1 = "SERVER";

class ConfigFile {

private:
    const std::string PortNum;

public:
    ConfigFile(std::string const& configFile);

    std::string GetPortNO()
    {
        return PortNum;
    }
    void Load_Server_Config();

    //std::string& operator= (const std::string& str);

};

#endif

ConfigFile.cpp

#include "ConfigFile.h"

#include <fstream>

std::string trim(std::string const& source, char const* delims = " \t\r\n") {
  std::string result(source);
  std::string::size_type index = result.find_last_not_of(delims);
  if(index != std::string::npos)
    result.erase(++index);

  index = result.find_first_not_of(delims);
  if(index != std::string::npos)
    result.erase(0, index);
  else
    result.erase();
  return result;
}

ConfigFile::ConfigFile(std::string const& configFile) {
  std::ifstream file(configFile.c_str());
  std::string temp;
  std::string line;
  std::string name;
  std::string value;
  std::string inSection;
  int posEqual;
  while (std::getline(file,line)) {

    if (! line.length()) continue;

    if (line[0] == '#') continue;
    if (line[0] == ';') continue;

    if (line[0] == '[') {
      inSection=trim(line.substr(1,line.find(']')-1));
      continue;
    }

    posEqual=line.find('=');
    name  = trim(line.substr(0,posEqual));
    value = trim(line.substr(posEqual+1));

    if (name.compare("Port") == 0)
    {
        PortNum = value;        
    }
  }
}


int main()
{
ConfigFile cf("test.ini");
return 0;
}

.iniファイル。。

[SERVER]
Port = 1234

ここで、PortNumは上記のコードのクラスConfigFileのメンバーであり、エラーC2678としてコンパイルエラーが発生します。binary'=':演算子 がありません。クラスに「=」オーバーロード演算子が存在しないためです。 "="マイクラスの演算子.....または別のクラスで文字列値をコピー/割り当てる方法はありますか...

上記のコードは、.iniファイルを読み取るように記述されています。このファイルでは、config Portが存在する場合、 PortNumの値を処理します。

私の質問に加えて、.iniファイルをロードする他の方法を選択できます。

4

2 に答える 2

2

ここで提案されているように、WindowsAPIまたはBoostProgram Optionsを使用するのはどうですか?C ++でINIファイルを解析する最も簡単な方法は何ですか?

于 2013-03-10T17:08:00.297 に答える
2

文字列に新しい値を割り当てようとしていconstます。つまり、その値を変更しようとしています。constオブジェクトを変更することはできません、それはconstです。

非定数にします。

于 2013-03-10T17:08:04.593 に答える