我提供了免费的版权模板代码,并根据自己的需要进行了修改,但仍在努力使其发挥作用。我希望能帮助你理解。
问题在于我并不真正理解超载是如何工作的,尤其是>>运算符,如下例所示。为什么要在friend& operator函数中返回对象logger
。我不明白如何让void print();
工作并与朋友超载operator <<
进行互动。
这是示例代码:
#pragma once
#include <fstream>
namespace Log{
class LogFile {
public:
enum class logType { LOG_ALWAYS=0, LOG_OKAY, LOG_ERROR, LOG_WARNING, LOG_INFO};
enum class writeType {FOUT=0, CFOUT, FCOUT, COUT};
explicit LogFile(string fname = "[nameError]log.txt") : numWarnings(0U), numErrors(0U)
{
myFile.open(fname);
if (myFile.is_open())
std::cout << "Log file was created successfully!" << std::endl << std::endl;
else
{
std::cout << "Fatal Error can't create log file!" << std::endl << "Please check Application permissions" << std::endl;
exit(1);
}
}
~LogFile()
{
if (myFile.is_open())
{
myFile << std::endl << std::endl;
myFile << numWarnings << " warnings" << std::endl;
myFile << numErrors << " errors" << std::endl;
myFile.close();
}
}
friend LogFile &operator << (LogFile &logger, const logType e_logtype)
{
//TO DO
//logger.myFile << tm << "| " << memUsed << "kb added|";
//<< "000000.000 | 0.0000kb added |"
switch (e_logtype)
{
case LogFile::logType::LOG_ALWAYS:
logger.myFile << " ALWAYS| ";
break;
case LogFile::logType::LOG_OKAY:
logger.myFile << " OKAY| ";
break;
case LogFile::logType::LOG_ERROR:
logger.myFile << " ERROR| ";
++logger.numErrors;
break;
case LogFile::logType::LOG_WARNING:
logger.myFile << " WARN| ";
++logger.numWarnings;
break;
default:
logger.myFile << " INFO| ";
break;
}
return logger;
}
friend LogFile &operator << (LogFile &logger, const char* text)
{
logger.myFile << tex t << std::endl;
return logger;
}
LogFile(const LogFile &) = delete;
LogFile &operator= (const LogFile &) = delete;
//THIS IS MY PART
friend void print(LogFile &logger, const char* text, const logType e_logtype, const writeType e_writetype)
{
switch (e_writetype)
{
case LogFile::writeType::FOUT:
logger << LogFile::logType::e_logtype << text;
break;
case LogFile::writeType::FCOUT:
case LogFile::writeType::CFOUT:
std::cout << text << std::endl;
logger << LogFile::logType::e_logtype << text;
break;
case LogFile::writeType::COUT:
default:
std::cout << text << std::endl;
break;
}
return;
}
private:
std::ofstream myFile;
unsigned int numWarnings;
unsigned int numErrors;
};
}
这个想法是使用它作为标题,并在main.cpp中使用:
记录所有内容using namespace Log;
LogFile mylog;
mylog.print("Test...", LOG_OKAY, FCOUT);
其中:
LOG_OKAY,LOG_ERROR等 - 日志信息的类型。
COUT,FCOUT,CFOUT,FOUT - 登录文件或cout或两者
编辑:我在3周前解决了这个问题。感谢@zenith的回答。如果问题再次打开,我会发布带有概述代码的解决方案,我已经改变了点数给他们。谢谢:)
答案 0 :(得分:1)
我真的不明白为什么你在朋友和运算符函数中返回对象
logger
。
这样你就可以链接多个调用:
logger << logtype << text << moretext;
如何让
void print
工作并与朋友互动operators <<
。
您可以删除LogFile::logType::
前面的e_logtype
来解决编译错误:
logger << e_logtype << text;
因为e_logtype
不是LogFile::logType
的成员,所以它是LogFile::logType
类型的对象。
此外,您还缺少#include <string>
using std::string
和#include <iostream>
。