axe_lankaster13
@axe_lankaster13
C++ разраб с большими планами

Как перегрузить оператор так, чтобы принимать std::endl в своём потоке вывода?

Пишу свой класс логгера.
Лог пишется в файл через std::ofstream.
Для того, чтобы использовать свой класс логгера подобно std::cout и std::ofstream, перегружаю оператор "<<".
Вопрос: Как перегрузить оператор "<<" так, чтобы он принимал std::endl ?

Код класса:
Log.h

class Log
{
private:
	std::ofstream _file;

public:
	Log(const std::string& path);
	~Log();

	Log& operator<<(const int value);
	Log& operator<<(const char ch);
	Log& operator<<(const char* chars);
	Log& operator<<(const std::string &string);
};


Log.cpp

Log::Log(const std::string& path)
	: _file(path)
{
	if (!_file.is_open())
	{
		throw std::runtime_error("Failed to open log file");
	}
}

Log::~Log()
{
	_file.close();
}

Log& Log::operator<<(const int value)
{
	_file << value;
	return *this;
}

Log& Log::operator<<(const char ch)
{
	_file << ch;
	return *this;
}

Log& Log::operator<<(const char* chars)
{
	_file << chars;
	return *this;
}

Log& Log::operator<<(const std::string& string)
{
	_file << string;
	return *this;
}

  • Вопрос задан
  • 88 просмотров
Решения вопроса 1
vt4a2h
@vt4a2h Куратор тега C++
Senior software engineer (C++/Qt/boost)
Вот тут есть примеры сигнатуры функции: https://en.cppreference.com/w/cpp/io/basic_ostream...
basic_ostream& operator<<(
    std::basic_ostream<CharT,Traits>& (*func)(std::basic_ostream<CharT,Traits>&) );
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы