重新定义,字符串的不同基本类型

redefinition , different basic types for string

本文关键字:类型 字符串 新定义 定义      更新时间:2023-10-16

loadFromTextFile.h

#include <string>
#include <vector>
#include <iostream>
#include <fstream>
#include <cstdlib>
class loadFromTextFile{
private:
    int rows = 0;
    int columns = 0;
    std::string file_path;
    std::vector<std::vector<std::string> > nodeGrid;
    void process(std::string);
public:
    loadFromTextFile(std::string);
    loadFromTextFile();
};

从文本文件加载.cpp

#include "loadFromTextFile.h"
using namespace std;
//implementions
loadFromTextFile::loadFromTextFile(string filePath){
    file_path = filePath;
    string line;
    ifstream f(file_path);
    if (!f.is_open())
        perror("error while opening file");
    while (getline(f, line)) {
        process(line);
    }
    if (f.bad())
        perror("error while reading file");
    cout << "total rows" << rows;
}
void loadFromTextFile::process(string s){
    rows++;
    cout << s<<endl;
}

main.cpp

#include "loadFromTextFile.h"
int main(){
    std::string path = "E:\10x10.txt"; 
    loadFromTextFile(path);
    //loadFromTextFile("E:\10x10.txt");//works
}

任何人都知道我为什么要重新定义"路径";字符串路径有不同的基本类型,但是当我直接传递字符串而不是使用变量路径时,它就起作用了。

loadFromTextFile(path);等价于loadFromTextFile path;,一个声明。

loadFromTextFile("E:\10x10.txt");不能被解释为一个声明,因此它被视为一个转换表达式,创建和销毁一个临时对象。它可以编译,但可能也不是您想要的。

您可能想要声明一个命名变量,这样它加载的数据在之后仍然可用:

loadFromTextFile loaded(path);