使用三元运算符从 cin 或文件中选择 istream

Selection of istream from cin or file with ternary operator

我想要一个 class 的成员变量,它根据用户输入的字符串存储输入流。例如

#include <string.h>
#include <iostream>
#include <fstream>

class myInput {
public:
    myInput(std::string file_name);
    myInput() = delete;

protected:
    std::istream& in_data;
};
 
myInput::myInput(std::string file_name)
    : in_data((file_name == "-") ? std::cin : std::ifstream(file_name)){}

void main() {
    myInput("file.txt");
}

但是我收到以下错误

error: use of deleted function ‘std::basic_istream<_CharT, _Traits>::basic_istream(const std::basic_istream<_CharT, _Traits>&) [with _CharT = char; _Traits = std::char_traits]’
error: ‘std::basic_istream<_CharT, _Traits>::basic_istream(const std::basic_istream<_CharT, _Traits>&) [with _CharT = char; _Traits = std::char_traits]’ is protected within this context

我也试过单独创建 ifstream 对象并将其分配给 in_data,但遇到类似的问题。这是为什么?

首先在程序中包含 #include <iostream> 头文件,它不应该在第二行

std::istream 不允许您执行类似 in_data = std::cinin_data = std::ifstream("file.txt") 的操作,因为赋值运算符已被删除。

另一种解决方案是使用指向 std::istream.

的指针
class myInput {
public:
    myInput(std::string file_name);
    virtual ~myInput() { if (bIsHeapAllocated) delete in_data; } // delete the heap allocation if done.
    myInput() = delete;

protected:
    std::istream* in_data = nullptr;
    bool bIsHeapAllocated = false;    // You can make this a private member if you don't want your inherited classes knowing this.
};

myInput::myInput(std::string file_name)
{
    if (file_name == "-")
        in_data = &std::cin;
    else
        in_data = new std::ifstream(file_name), bIsHeapAllocated = true;    // Allocate the ifstream in heap
}