有没有一种方法可以传入对对象的流引用
Is there a way to pass in a ofstream reference to a object?
我正试图将对一个具有打开文件的ofstream的引用传递给一个对象,这样它的函数也可以打印到该文件中。
当我试图编译我的程序时,它说所有引用成员都必须初始化,我在网上读到流不能重新分配。那我该怎么办?
以下是我为我的构建者准备的:
GameShow::GameShow(int numElements){
// Initialize heap
v = new Contestant[numElements+1];
capacity = numElements+1;
size = 0;
}
GameShow(int numElements, std::ofstream &of)
: outFile(of){
// Initialize heap
v = new Contestant[numElements+1];
capacity = numElements+1;
size = 0;
outputToFile = true;
handle.reserve(numElements+1);
handle.resize(numElements+1, -1);
}
这是我在头文件中的声明:
// Members
....
ofstream &outFile;
....
GameShow(int numElements);
GameShow(int numElements, std::ofstream &of);
....
我在main()函数中打开了ofstream,但我的对象函数需要能够修改同一个文件。。。我觉得我什么都试过了。
当我尝试传入文件名,并尝试在对象中以附加模式打开它并打印到它时,输出完全无序,与主函数的输出完全不同步。我从对象调用的所有print语句似乎都被保存在缓冲区中,直到我的主函数关闭了流的末尾。如有任何帮助,我们将不胜感激。
尝试在我的主函数中使用构造函数
// Attempt to open output file
ofstream outFile;
outFile.open(outFileName);
if(inFile.is_open()){
if(outFile.is_open()){
// Get information
int numContestants = 0;
inFile >> numContestants;
// Process file
if(numContestants > 0){
GameShow gs(numContestants, outFile);
错误(我得到的唯一错误):
GameShow.cpp: In constructor ‘GameShow::GameShow(int)’:
GameShow.cpp:27:1: error: uninitialized reference member in ‘std::ofstream& {aka class std::basic_ofstream<char>&}’ [-fpermissive]
GameShow::GameShow(int numElements){
^
GameShow.h:14:18: note: ‘std::ofstream& GameShow::outFile’ should be initialized
std::ofstream &outFile;
^
make: *** [GameShow.o] Error 1
GameShow(int numElements)
构造函数中初始化outFile
。
从错误消息中,您似乎有了另一个构造函数:
GameShow(int numElements);
在该构造函数的实现中,您没有初始化变量outFile
。我不确定将该变量初始化为什么合适的值。如果您将变量更改为类型std::ostream
,则可以将其初始化为std::cout
。
改为引用为成员用户指针。
ofstream*outFile;
GameShow(int numElements,std::ofstream*of);
相关文章:
- 返回常量对象引用 (getter) 和仅返回字符串有什么区别?
- 我们可以有一个 setter 成员函数作为从 const 对象引用的 const 吗?
- C++对象引用返回不同的值
- 对象引用中的字段以不同的方法返回不同的值
- 通过向构造函数其他对象引用页面来创建对象
- 为什么在对象引用恒定时允许更改为另一个类的指针的成员变量
- 如何在C++中读取 HDF5 对象引用
- C++ 未定义的对象引用
- 从函数返回 libconfig 类设置对象引用
- qt vsaddin错误对象引用未设置为对象的istanse
- 在这种情况下,为什么使用 *此必需的对象引用返回对象引用
- 基本C - 构造contaning对象引用,并将其作为方法参数传递
- C :将对象引用作为参数给出错误:呼叫class :: function()的匹配函数
- C++OOP基础知识-是否正确返回对象引用
- 使用对象引用(可能)在调用destructor后使用对象引用
- 创建返回对象引用的成员函数的最简单方法
- 如何在C++上使用对象引用删除对象
- JNI/Android NDK-维护全局对象引用
- 为什么有些类方法返回"*this"(self的对象引用)?
- 在C++中返回伪对象引用的规则