有没有一种方法可以传入对对象的流引用

Is there a way to pass in a ofstream reference to a object?

本文关键字:对象 引用 方法 一种 有没有      更新时间:2023-10-16

我正试图将对一个具有打开文件的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);