gpt4 book ai didi

C++类重定义错误

转载 作者:搜寻专家 更新时间:2023-10-31 00:21:13 26 4
gpt4 key购买 nike

我正在编译一个日志记录程序,但是我收到了这个错误并且我无法解决这个问题...

logger.cpp:15: error: redefinition of ‘class Logger’
logger.h:20: error: previous definition of ‘class Logger’

编译时用gcc

g++ -Wall logger.cpp -o log

记录器.h:

#ifndef LOGGER_H
#define LOGGER_H

#include <fstream>
#include <iostream>
#include <string>
using std::string;

class Logger
{

static Logger* m_pInstance;

public:
static Logger* Instance() { return m_pInstance; }
void writeLog(string message);
void openLogFile(string fileName);
void closeLogFile();
void deleteLogger();

};
#endif

记录器.cpp

#include "logger.h"

#include <fstream>
#include <iostream>

class Logger
{
static Logger* m_pInstance;
std::ofstream m_pOutputFile;
Logger()
{
}
~Logger()
{
}

public:
static Logger* Instance()
{
if(!m_pInstance)
{
m_pInstance = new Logger;
}
return m_pInstance;
}
void writeLog(std::string message)
{
m_pOutputFile << message << "\n";
std::cout << "you just wrote " << message << " to the log file!\n" << std::endl;
}
void openLogFile(std::string fileName)
{
m_pOutputFile.open(fileName.c_str(),std::ios::out);
}
void closeLogFile()
{
m_pOutputFile.close();
}
void deleteLogger()
{
delete m_pInstance;
}
};
Logger* Logger::m_pInstance = NULL;

最佳答案

这正是错误信息所说的。实现文件不能随心所欲地提供类的重新定义,添加新的成员变量和冲突的函数体。相反,为您已经声明的函数和静态成员变量提供定义。

#include "logger.h"

#include <fstream>
#include <iostream>


static Logger::Logger* m_pInstance;

Logger::Logger()
{
}

Logger::~Logger()
{
}

// this also is illegal, there's a body provided in the header file
//Logger* Logger::Instance()
//{
// if(!m_pInstance)
// {
// m_pInstance = new Logger;
// }
// return m_pInstance;
//}

void Logger::writeLog(std::string message)
{
m_pOutputFile << message << "\n";
std::cout << "you just wrote " << message << " to the log file!\n" << std::endl;
}

等等

关于C++类重定义错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4902639/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com