C++ 重载输出运算符。

4

我有一个头文件,看起来像这样:

#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问题,但据我所知,我正确地重载了运算符的格式。

1个回答

3
在您的.cpp文件中,不要使用using,而是声明正确的命名空间:
namespace microtask
{
    namespace log
    {
        ::std::ostream & operator<<(::std::ostream& out, const severity& level)
        {
            // ...
        }
    }
}

实际上,如果可以的话,不要随意使用using。在我看来,它应该被保留用于显式基类成员取消隐藏和ADL请求。

好的,这样做可以。现在为了不再犯同样的错误,之前为什么不能工作呢?(等时间结束后,我会接受你的答案)。 - ctrlc-root
你定义的是 ::operator<<,而不是 microtask::log::operator<<。那只是一个单独的函数,你需要的那个还没有定义。永久解决方案甚至连你的孙子都会感激不尽,就是永远不要使用 using :-) - Kerrek SB
啊,我明白了,那么这样做也说得通。我不知道,只是因为我习惯像那样为类方法声明实现,所以有点摸不着头脑。 - ctrlc-root
@root.ctrlc 我认为你的版本无法工作的原因是因为你在 .cpp 文件中定义的 operator<< 实现了 ::operator<<(out, severity),但没有实现 microtask::log::operator<<(out,severity)。 - flumpb
@root.ctrlc:实际上,我无法复现你所说的情况。如果你能让它正常工作,请发布一个新问题并询问为什么查找有效。 - Kerrek SB
显示剩余5条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接