C++ 将 ifstream 转换为 istream

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4080179/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 14:30:10  来源:igfitidea点击:

Convert ifstream to istream

c++casting

提问by Anonymous

How would one go about casting a ifstream into a istream. I figure since ifstream is a child of istream I should be able to do so but I have been having problems with such a task.

如何将 ifstream 转换为 istream。我想既然 ifstream 是 istream 的孩子,我应该能够这样做,但我在执行这样的任务时遇到了问题。

std::istream & inputStr = std::cin;
  std::ostream & outputStr = std::cout;
  if(argc == 3){
    std::fstream inputFile;
    inputFile.open(argv[1], std::fstream::in);
    if(!inputFile){
        std::cerr << "Error opening input file";
        exit(1);
    }
    inputStr = inputFile;
.....
}

回答by Cheers and hth. - Alf

No cast is necessary.

不需要演员表。

#include <fstream>
int main()
{
    using namespace std;
    ifstream    f;
    istream&    s   = f;
}

回答by Steve Guidi

Try:

尝试:

std::ifstream* myStream;
std::istream* myOtherStream = static_cast<std::istream*>(myStream);
myOtherStream = myStream;   // implicit cast since types are related.

The same works if you have a reference (&) to the stream type as well. static_castis preferred in this case as the cast is done at compile-time, allowing the compiler to report an error if the cast is not possible (i.e. istreamwere not a base type of ifstream).

如果您也有对流类型的引用 (&),则同样有效。 static_cast在这种情况下是首选,因为强制转换是在编译时完成的,如果强制转换是不可能的(即istream不是 的基本类型ifstream),则允许编译器报告错误。

Additionally, and you probably already know this, you can pass a pointer/reference to an ifstreamto any function accepting a pointer/reference to a istream. For example, the following is allowed by the language:

此外,您可能已经知道这一点,您可以将指向 的指针/引用传递ifstream给任何接受指向 的指针/引用的函数istream。例如,语言允许以下内容:

void processStream(const std::istream& stream);

std::ifstream* myStream;
processStream(*myStream);

回答by Neil

std::istream *istreamObj = dynamic_cast<std::istream *>(&ifStreamObj)