【问题标题】:return and call dynamic string array返回并调用动态字符串数组
【发布时间】:2013-03-18 11:47:55
【问题描述】:

我创建了一个类:

    Data::Data(char szFileName[MAX_PATH]) {

    string sIn;
    int i = 1;

    ifstream infile;
    infile.open(szFileName);
    infile.seekg(0,ios::beg);

    std::vector<std::string> fileRows;
    while ( getline(infile,sIn ) )
    {
      fileRows.push_back(sIn);
    }
}

之后我创建了这个:

std::vector<std::string> Data::fileContent(){
        return fileRows;
}

在那之后,我想在某个地方称它为 fileContent(),如下所示:

Data name(szFileName);
MessageBox(hwnd, name.fileContent().at(0).c_str() , "About", MB_OK);

但这不起作用...如何调用它?

【问题讨论】:

  • 什么是Adatkezeles?
  • 我猜你想让fileRows 成为Data 的成员?
  • 对不起 Adatkezeles = 数据数据名称(szFileName); MessageBox(hwnd, name.fileContent().at(0).c_str() , "关于", MB_OK);我得到了这个错误:在抛出 'std::out_of_range' what() 的实例后调用终止:vector::_M_range_check
  • @David:请使用edit 链接使用此信息更新您的问题。此外,您可能希望 Data::fileContent() (a) 成为 const-qualified 并且 (b) 通过引用返回 std::vector&lt;std::string&gt;。

标签: c++ string function vector


【解决方案1】:
std::vector<std::string> fileRows;
while ( getline(infile,sIn ) )
{
   fileRows.push_back(sIn);
}

不起作用,因为您在构造函数中声明了 fileRows,一旦构造函数结束,fileRows 就会被销毁。

你需要做的是将fileRows声明移到构造函数之外并使其成为类成员:

class Data
{
...

   std::vector<std::string> fileRows;
};

那么它将被类中的所有函数共享。

【讨论】:

    【解决方案2】:

    你可以这样做:

    #include <string>
    #include <vector>
    
    class Data
    {
    public:
      Data(const std::string& FileName)  // use std::string instead of char array
      {
         // load data to fileRows
      }
    
      std::string fileContent(int index) const  // and you may don't want to return a copy of fiileRows
      {
          return fileRows.at(index);
      }
    
    private:
        std::vector<std::string> fileRows;
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-13
      • 1970-01-01
      • 2018-02-07
      • 1970-01-01
      • 1970-01-01
      • 2015-05-24
      • 2013-01-18
      • 1970-01-01
      相关资源
      最近更新 更多