c++ - 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.
解决方案
在fileOutput.h
标题中,您为该类 声明一个静态数据成员:
static fileOutput *instance;
该成员必须在某处定义。因此缺少的是fileOutput.cpp
:
fileOutput *fileOutput::instance;
推荐阅读
- r - 首先过滤那些具有连续值的
- html - 我看不到我在引导程序中添加的箭头图标
- python - ctypes dll变量声明
- sql - 如何将变量传递给存储过程以更新另一个数据库中的行?
- python - 如何用熊猫中的第一个非零值替换一行中的值?
- google-apps-script - 防止谷歌表格 IF(TODAY()) 函数在某个日期之后编辑
- oracle - ORA-12839 当我在我的 ATP 实例中使用并行 DML 时?
- android - 如何在自定义 Activity/Fragment 中显示 Android OSS 许可证 Activity
- java - 在java中查找包含子字符串的数组的所有出现
- javascript - 反应传单给窗口未定义的错误