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

标签 c++

加载文本文件.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;

}

主要.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);

关于c++ - 重新定义,字符串的不同基本类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28834345/

相关文章:

c++ - "sum root to leaf numbers"问题的解决方案

c++ - 如何将 C/C++ printf() 消息重定向到 Windows Phone 日志系统

c++ - 如何使用 std::fstream 以可移植的方式处理二进制文件?

c++ - 在类模板的成员枚举上重载运算符

c++ - 将 COM 对象返回给 JScript

c++ - 如何使用模板表达成员之间的约束?

c++ - PostgreSQL 将数组或记录作为行返回

c++ - 在外联定义成员函数时,哪些限定符必须出现在声明/定义/两者中?

c++ - 动态添加覆盖小部件

c++ - 是否有复制 visual studio C++ 自动缩进样式的命令行工具?