[英]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.