C ++-尝试打印到具有许多类的控制台和文件吗?

问题描述 投票:1回答:1

因此,我尝试使用许多类同时打印到控制台和文本文件。

class Assignment {
    static std::ostream &_rout;

};

//Method to print to a text file
void print(std::ostream& os1, std::ostream& os2, const std::string& str)
{
    os1 << str;
    os2 << str;
}
std::ofstream file("Game.txt");

std::ostream &Assignment::_rout(file);

然后在我要在同一类中打印(打印)的任何地方使用该打印方法。

但是我知道我需要进行更改,因为我不能在多个课程中都这样做。所以我创建了一个文件输出类:

fileOutput.h

class fileOutput {
    string filename;


    static fileOutput *instance;

    fileOutput();

public:
    static fileOutput *getInstance() {
        if (!instance)
        {
            instance = new fileOutput();
        }
        return instance;
    };

    void toPrint(string value);
};

filoutput.cpp

#include <fstream>
#include <cstddef>
#include "fileOutput.h"

fileOutput::fileOutput() {

    ofstream myfile;
    myfile.open("output.txt", ios::out | ios::app);
}

void fileOutput::toPrint(string value) {
    cout << value;
    ofstream myfile;
    myfile.open("output.txt", ios::out | ios::app);
    myfile << value;
    myfile.close();

}

当我尝试在Deck类中创建fileOuput的实例并使用toPrint方法时:

#include "fileOutput.h"
using namespace std;

void Deck::chooseHand() {
    fileOutput *print = print->getInstance();

    int count = 0;
    vector<Card> hand; //Create a new smaller deck(hand)
    while (count < MAXHANDSIZE)
    {
    int cardno;

    //This line underneath
    print->toPrint("Please select a Card:(1-20) ");

hand.push_back(cardDeck[cardno - 1]);
    count++;//increment count
    }
    curr_size = MAXHANDSIZE;
    cardDeck.clear();// Get rid of the rest of the deck
    cardDeck = hand; //hand becomes the new deck
}

我似乎收到此错误:

1>Deck.obj : error LNK2001: unresolved external symbol "private: static class fileOutput * fileOutput::instance" (?instance@fileOutput@@0PEAV1@EA)
1>C:\Users\hamza\Desktop\Assignment (2)\Assignment\x64\Debug\Assignment.exe : fatal error LNK1120: 1 unresolved externals
1>Done building project "Assignment.vcxproj" -- FAILED.
c++
1个回答
0
投票

fileOutput.h标头中,为该类声明static data member

static fileOutput *instance;

此成员必须在某处定义。因此,缺少的是fileOutput.cpp中的一行:

fileOutput *fileOutput::instance;  
© www.soinside.com 2019 - 2024. All rights reserved.