简体   繁体   English

如何将一个对象定义为一种类型,然后再将其声明为子类型?

[英]How can I define an object as one type, then later declare it as a sub-type?

I have some code that needs to read in data, either from an istringstream or an ifstream. 我有一些代码需要从istringstream或ifstream读取数据。 I don't know much about C++, but my experience in other languages tells me I should just have a variable that's an istream (the parent type of ifstream and istringstream), and then later set it to either an istringstream or an ifstream. 我对C ++不太了解,但是我在其他语言中的经验告诉我,我应该只拥有一个istream变量(ifstream和istringstream的父类型),然后再将其设置为istringstream或ifstream。 Here's what this might look like in, say, Java: 例如,这是在Java中的样子:

String word;
IStream stream;

if (someCondition) {
    stream = new IStringStream("banana");
} else {
    stream = new IFStream("apple.txt");
}

while (word = is.read()) {
    // do some stuff
}

This type of syntax would work no problem in Java and other similar languages, but I can't get it to work in C++. 这种语法在Java和其他类似语言中不会有问题,但是我无法在C ++中使用它。 Here's what my code looks like right now: 这是我的代码现在的样子:

string word;
istream stream;

if (someCondition) {
    string mystr = "banana";
    istringstream stream(mystr);
} else {
    string myfile = "apple.txt";
    ifstream stream(myfile);
}

while(stream >> word) {
    // do some stuff
}

This doesn't compile, with the error on the 2nd line: "no matching constructor for initialization of 'istream' (aka 'basic_istream')". 这不会编译,并在第二行显示错误:“没有匹配的构造函数来初始化'istream'(又名'basic_istream')”。 What can I change to make the C++ code work like the Java pseudocode example I wrote above does? 为了使C ++代码像我上面编写的Java伪代码示例一样工作,我需要做些什么更改?

Since you are coming from Java, a quick rule of thumb is that for polymorphic objects you need a pointer (asterisk * ), a reference (ampersand & ), a smart pointer, or some other way of setting up indirection. 由于您来自Java,因此快速的经验法则是,对于多态对象,您需要一个指针(星号* ),一个引用(&符& ),智能指针或其他设置间接方式的方法。

Here is an example of the syntax that would fix the problem: 这是解决该问题的语法示例:

string word;
istream *stream;

if (someCondition) {
    string mystr = "banana";
    stream = new istringstream(mystr);
} else {
    string myfile = "apple.txt";
    stream = new ifstream(myfile);
}

while((*stream) >> word) {
    // do some stuff
}

delete stream;

Note: This solution is not ideal, because you end up deleting the stream manually. 注意:此解决方案不是理想的,因为您最终将手动删除流。 A better approach would rely on a smart pointer, which deletes your object automatically. 更好的方法是依靠智能指针,该指针会自动删除对象。

You should put the part that uses the stream in a function that takes a std::istream& and then just pass in whatever you want to use. 您应该将使用流的部分放在带有std::istream&的函数中,然后只需传入您想使用的任何内容。

#include <iostream>
#include <sstream>
#include <fstream>

void useStream(std::istream& stream) {
    std::string word;
    while (stream >> word)
        std::cout << word << ' ';
}

int main() {
    if (someCondition) {
        std::string str = "The best program in the world";
        std::stringstream foo(str);
        useStream(foo);
    }
    else {
        std::ifstream file("text.txt");
        useStream(file);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从模板类中获取“子类型” - Getting a “sub-type” from a template class 基础构造函数根据输入调用派生构造函数 - 在运行时选择对象子类型 - Base constructor calls derived constructor depending on input - Choose object sub-type at runtime 我可以声明未知类型的本征矩阵,还是至少声明一个泛型矩阵并稍后实例化? - Can i declare an Eigen matrix of unknown type, or at least declare a generic matrix and instantiate later? 如何声明模板常量类型? - How can I declare a template constant type? 有条件地启用子类型(类似于enable_if以启用函数) - Conditionally enable a sub-type (similar to enable_if to enable functions) 如何声明和定义具有推导类型的静态成员? - How to declare and define a static member with deduced type? 如何在LLVM中声明函数并在以后定义它 - How to declare a function in LLVM and define it later 如何在类中声明一个类并在以后定义它? - How to declare a class inside a class and define it later on? 我可以定义一个指向std :: function类型对象的函数指针吗? - Can I define a function pointer pointing to an object of std::function type? C ++ 11:如何定义一个接受特定类型对象的通用引用的函数? - C++11 : How can I define a function that accept a universal reference of a specific type of object?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM