【发布时间】:2015-03-06 07:05:22
【问题描述】:
我正在尝试将带有打开文件的 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,但我的对象函数需要能够修改同一个文件...我觉得我已经尝试了所有方法。
当我尝试传入文件名并尝试在对象中以附加模式打开它并打印到它时,输出完全乱序并且与我的主函数的输出完全不同步。似乎我从对象调用的所有打印语句都保存在缓冲区中,直到我的主函数结束了流。任何帮助将不胜感激。
尝试在我的主函数中使用构造函数:
// 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
【问题讨论】:
-
不要声明引用 (
ofstream &outFile;),声明一个对象并通过引用将该对象传递给函数。 -
@MariusBancila 我想这是我唯一的选择。真的没有办法传递对对象的引用吗??
-
您展示的代码没有任何问题。显示其余部分以及更精确的错误消息。
-
@BenjaminLindley 给我一分钟,我会发帖
-
@JayB 您要问的是如何初始化对象的引用数据成员。您应该发布一个包含失败代码的 MCVE,因为原则上它不应该是一个问题。
标签: c++ oop object reference ofstream