C++重载输出运算符
我有一个如下所示的头文件:
#pragma once
//C++ Output Streams
#include <iostream>
namespace microtask
{
namespace log
{
/**
* Severity level.
*/
enum severity
{
debug,
info,
warning,
error,
critical
};
/**
* Output the severity level.
*/
std::ostream& operator<<(std::ostream& out, const severity& level);
}
}
和一个如下所示的源文件:
//Definitions
#include "severity.hpp"
//Namespaces
using namespace std;
using namespace microtask::log;
std::ostream& operator<<(std::ostream& out, const severity& level)
{
switch(level)
{
case debug:
out << "debug";
break;
case info:
out << "info";
break;
case warning:
out << "warning";
break;
case error:
out << "error";
break;
case critical:
out << "critical";
break;
default:
out << "unknown";
break;
}
return out;
}
我正在尝试将其编译为动态库。不幸的是,链接失败并显示以下错误消息:
undefined reference to `microtask::log::operator<<(std::basic_ostream<char, std::char_traits<char> >&, microtask::log::severity const&)'
我做错了什么?我检查了其他看起来类似的 stackoverflow.com 问题,但据我所知,我的重载运算符的格式是正确的。
I have a header file that looks like this:
#pragma once
//C++ Output Streams
#include <iostream>
namespace microtask
{
namespace log
{
/**
* Severity level.
*/
enum severity
{
debug,
info,
warning,
error,
critical
};
/**
* Output the severity level.
*/
std::ostream& operator<<(std::ostream& out, const severity& level);
}
}
and a source file that looks like this:
//Definitions
#include "severity.hpp"
//Namespaces
using namespace std;
using namespace microtask::log;
std::ostream& operator<<(std::ostream& out, const severity& level)
{
switch(level)
{
case debug:
out << "debug";
break;
case info:
out << "info";
break;
case warning:
out << "warning";
break;
case error:
out << "error";
break;
case critical:
out << "critical";
break;
default:
out << "unknown";
break;
}
return out;
}
that I am trying to compile into a dynamic library. Unfortunately, linking fails with this error message:
undefined reference to `microtask::log::operator<<(std::basic_ostream<char, std::char_traits<char> >&, microtask::log::severity const&)'
What am I doing wrong? I've checked other stackoverflow.com questions that seemed similar, but as far as I can tell, I have the format for overloading the operator correct.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在您的 .cpp 文件中,不要说
using
,而是声明正确的命名空间:事实上,如果可以的话,根本不要随意说
using
。在我看来,它应该保留用于显式的基本成员取消隐藏和 ADL 请求。In your .cpp file, don't say
using
, but instead declare the proper namespace:In fact, don't say
using
casually at all if you can help it. In my opinion it should be reserved for explicit base member unhiding and ADL requests.