首页 > 解决方案 > C++ - 试图打印到控制台和有很多类的文件?

问题描述

所以我正在尝试使用许多类打印到控制台和文本文件。

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);

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

但我知道我需要改变它,因为我不能为多个班级这样做。所以我创建了一个文件输出类:

文件输出.h

class fileOutput {
    string filename;


    static fileOutput *instance;

    fileOutput();

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

    void toPrint(string value);
};

文件输出.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++

解决方案


fileOutput.h标题中,您为该类 声明一个静态数据成员:

static fileOutput *instance;

该成员必须在某处定义。因此缺少的是fileOutput.cpp

fileOutput *fileOutput::instance;  

推荐阅读