2

我创建了一个类:

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

但这不起作用......如何称呼这个?

4

2 回答 2

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

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

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

class Data
{
...

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

然后它将由类中的所有函数共享。

于 2013-03-18T11:55:01.423 回答
1

你可以这样做:

#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;
};
于 2013-03-18T11:56:12.140 回答