【问题标题】:Pass a file as a parameter and read it from a constructor [closed]将文件作为参数传递并从构造函数中读取它[关闭]
【发布时间】:2014-05-27 00:31:06
【问题描述】:

我在将文件传递给构造函数时遇到问题

#include "WordList.h"
#include<iostream>
#include<fstream>
using namespace std;

WordList::WordList(ifstream& infile){}

-----
int main()
{
    WordList w1("input.txt");
}

这里显示错误:

No instance of constructor matches the argument list, the argument types are (const char[10])

那么如何通过构造函数传递文件。

【问题讨论】:

    标签: c++ file input constructor ifstream


    【解决方案1】:
     ifstream strm ("input.text", ifstream::in) ;
     WordList w1 (strm) ;
    

    你也可以定义WordList的构造函数,以istream & 作为参数来泛化例程。

    【讨论】:

    • 为什么我不能只传递“input.txt”作为参数,比如
    • 词汇表 w1("input.txt")
    • 因为 (a) ifstream 的构造函数是显式的,不能用于隐式转换,并且 (b) 即使允许隐式转换,它也会使用一个临时对象,它可以' t 绑定到非 const 左值引用。
    猜你喜欢
    • 2023-04-09
    • 2018-10-07
    • 1970-01-01
    • 2015-08-02
    • 2016-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-13
    相关资源
    最近更新 更多