【发布时间】:2016-09-02 20:43:16
【问题描述】:
以前,我会将 fstream 对象的地址传递给任何执行 I/O 操作的函数,包括构造函数。但我想尝试使 fstream 对象可用作成员变量,以便所有后续 I/O 操作都可以使用这些变量,而不是将它们作为参数传递。
考虑以下 Java 程序:
public class A {
Scanner sc;
public A(Scanner read) {
sc = read;
}
}
C++ 的等价物是什么?我试过这样做
class A {
ofstream *out;
public:
A (ofstream &output) {
out = output;
}
};
但这给了我一个编译错误:
[错误] 从 'std::ofstream {aka std::basic_ofstream}' 到 'std::ofstream* {aka std::basic_ofstream*}' 的用户定义转换无效 [-fpermissive]
【问题讨论】:
-
您不能将引用分配给指针。这些是不同的东西。
-
“但这给了我一个编译错误。”具体说明编译错误。请发minimal reproducible example!
-
另外,您要求的是输出,而不是像 scanner 所暗示的输入。
-
你是对的,但我要求的是一般 I/O 操作。我使用哪一个对我来说并不重要。至于编译错误,我将编辑我的原始帖子以包含它。