返回并调用动态字符串数组
return and call dynamic string array
我创建了一个类:
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;
};
相关文章:
- 将C#字符串数组传递给C++
- 如何为 C 型字符串数组编写 getter 和 setter?
- 有没有办法使用 strcpy 将字符串数组复制到另一个字符串或其他数组中?
- 尝试将 c 字符串数组与分隔符连接起来
- 将字符串数组传递给接受常量字符**的函数
- 返回 C++ 中的字符串数组
- 如何从COM模块中的函数返回字符串数组?
- 无法将字符串数组声明为类成员而不是字符 (C++)
- 删除字符串数组
- 如何将字符串数组返回到 java JNI
- 将字符串数组作为函数参数传递
- C++将字符串数组的元素存储到变量中
- 循环访问还包含未使用元素的字符串数组
- 字符串数组上的 sizeof 运算符以 C++ 为单位给出不同的输出
- 乘以字符串/数组和全局数组
- 递归二进制搜索与字符串数组
- 如何初始化一个标准::字符串数组?
- 无法在声明时使用初始值设定项列表初始化常量字符*/字符串数组的向量
- C++字符串数组的动态向量
- 给定一个等长字符串数组