如何将对象定义为一种类型,然后再将其声明为子类型
How can I define an object as one type, then later declare it as a sub-type?
我有一些代码需要从 istringstream 或 ifstream 读取数据。我对C++了解不多,但我在其他语言方面的经验告诉我,我应该只有一个变量,它是一个 istream(ifstream 和 istringstream 的父类型(,然后再将其设置为 istringstream 或 ifstream。下面是在Java中的样子:
String word;
IStream stream;
if (someCondition) {
stream = new IStringStream("banana");
} else {
stream = new IFStream("apple.txt");
}
while (word = is.read()) {
// do some stuff
}
这种类型的语法在 Java 和其他类似语言中没有问题,但我无法让它在 C++ 中工作。这是我的代码现在的样子:
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
}
这不会编译,第 2 行出现错误:"没有用于初始化 'istream'(又名'basic_istream'(的匹配构造函数"。我可以更改哪些内容以使C++代码像我上面编写的 Java 伪代码示例一样工作?
由于您来自Java,因此快速的经验法则是,对于多态对象,您需要指针(星号*
(,引用(与号&
(,智能指针或其他设置间接寻址的方法。
下面是可以解决此问题的语法示例:
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;
请注意: 此解决方案并不理想,因为您最终会手动删除流。更好的方法是依赖于智能指针,它会自动删除对象。
您应该将使用
流的部分放在一个接受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);
}
}
相关文章:
- '{'标记之前的预期类名,然后在预声明时无效使用不完整的类型'class class_name'
- 如何对绑定的成员方法进行typedef,然后将该类型用作模板参数
- 将函数应用于元组中的每个元素,将每个元素强制转换为类型包中的不同类型,然后作为参数包传递
- 强制复制(然后销毁)仅移动类型
- 如何将两个 jlong 数据类型转换为 jstring,然后将两个字符串连接在一起以便从 JNI 将字符串返回给 jav
- 如何将对象定义为一种类型,然后再将其声明为子类型
- 将转换范围缩小到更大的类型(然后再回来)
- static_cast到其他类型,然后移动结果
- 我可以做一个不形式的写入文件,然后从文件中进行整体类型的格式读取
- C/C++对一块内存进行malloc,然后对不同的任意类型使用不同的部分
- c++我需要将文件中的数据读取到多维数组中,然后用一种数据类型对数组进行排序.怎样
- 如何将 void 指针类型转换为 int 指针,然后在其中存储 int
- 复制构造,然后访问任意POD类型
- 为什么一旦我将引用声明为 const 然后它可以采用不同类型的数据?
- 对更复杂/结构化的类型使用boost::stream,然后使用chars
- 在C++中,我们可以向上转换一个数组,然后尝试将另一个子类型放入其中吗(灵感来自Java ArrayStoreExcep
- c++ 11: bind std::sort用于用户定义的类型,然后使用该绑定作为ctor的参数
- 如何在类名careercenter中定义数组类型customers,然后在.cpp文件中定义create, modify
- 为什么将类型转换为指针然后解引用可以工作?
- c++(98) STL是否可以设置对int类型的数组进行散列,然后检查该数组是否存在于集合中?