For this program, I want to use Singleton Design Pattern. This program is doing a logger particularly. When one instance is created, it first opens one file. Then when public method report(const string&) invoked, it appends the string to the end of the file. When the program exits, the stream should be closed.
Here are my code:
Logger.h
class Logger{
public:
static Logger& instance(){
static Logger log;
return log;
}
void report(const string&);
private:
Logger();
Logger(const Logger&){}
Logger& operator=(const Logger&){}
static void clean();
std::ofstream logFile_;
};
main.cpp
#include <iostream>
#include <fstream>
using std::string;
#include "Logger.h"
using std::cout; using std::endl;
void Logger::clean(){
// logFile_.close();
};
Logger::Logger(){
logFile_ = std::ofstream("log.txt", std::ios::out);
std::atexit(&clean);
}
void Logger::report(const string& comment){
// logFile_ << comment;
// logFile_.flush();
}
int main() {
string comment = "Initialization";
Logger::instance().report("");
Logger& logger1 = Logger::instance();
logger1.report(comment);
Logger& logger2 = Logger::instance();
logger2.report(comment);
return 0;
}
For my purpose, I should use static ofstream in function clean() in this case, so I changed by logFile declaration to static std::ofstream logFile_, but this gives an link error:
Undefined symbols for architecture x86_64: "Logger::logFile_", referenced from: Logger::Logger() in main-158c70.o ld: symbol(s) not found for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation)
My platform is Mac OS 10.12, compile command is Clang++ -std=c++11 main.cpp
Is there any possible solution to this problem? Or is there another way to do the coding?
Aucun commentaire:
Enregistrer un commentaire