返回并调用动态字符串数组

return and call dynamic string array

本文关键字:字符串 数组 动态 调用 返回      更新时间:2023-10-16

我创建了一个类:

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

但这不起作用。。。怎么称呼这个?

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

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

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

class Data
{
...
   std::vector<std::string> fileRows;
};

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

您可以这样做:

#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;
};