如何将 fstream 对象用作成员变量?
How can I use an fstream object as a member variable?
以前,我会将 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;
}
};
但这给了我一个编译错误:
[Error] invalid user-defined conversion from 'std::ofstream {aka std::basic_ofstream}' to 'std::ofstream* {aka std::basic_ofstream*}' [-fpermissive]
你可能想要
class A {
ofstream *out;
public:
A (ofstream &output) : out(&output) {
// ^ Take the address
}
};
由于 std::ofstream
专门用于文件,更好的接口是:
class A {
ostream *out;
public:
A (ostream &output) : out(&output) {
}
};
因此,您也可以将 class 透明地用于非面向文件的输出目标,例如
A a(std::cout); // writes to standard output rather than using a file
我建议使用引用类型作为class的成员变量。
class A {
ofstream& out;
public:
A (ofstream &output) : out(output) {}
};
它比使用指针更干净。
如果您希望 A
类型的对象从流中读取数据(如名称 Scanner
所暗示的那样),请使用 std::istream
.
class A {
std::istream& in;
public:
A (std::istream &input) : in(input) {}
};
以前,我会将 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;
}
};
但这给了我一个编译错误:
[Error] invalid user-defined conversion from 'std::ofstream {aka std::basic_ofstream}' to 'std::ofstream* {aka std::basic_ofstream*}' [-fpermissive]
你可能想要
class A {
ofstream *out;
public:
A (ofstream &output) : out(&output) {
// ^ Take the address
}
};
由于 std::ofstream
专门用于文件,更好的接口是:
class A {
ostream *out;
public:
A (ostream &output) : out(&output) {
}
};
因此,您也可以将 class 透明地用于非面向文件的输出目标,例如
A a(std::cout); // writes to standard output rather than using a file
我建议使用引用类型作为class的成员变量。
class A {
ofstream& out;
public:
A (ofstream &output) : out(output) {}
};
它比使用指针更干净。
如果您希望 A
类型的对象从流中读取数据(如名称 Scanner
所暗示的那样),请使用 std::istream
.
class A {
std::istream& in;
public:
A (std::istream &input) : in(input) {}
};