如何使运算符超载<<从名称空间中 [英] How to overload the operator<< from within a namespace

查看:65
本文介绍了如何使运算符超载<<从名称空间中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我能想到的最小的示例. 首先是该类的标题.每当<<使用了运算符.

This is the smallest contained example I can think of. First the header of the class. This class should simply print the one double it contains whenever the << operator is used.

#pragma once
#ifndef EURO_H
#define EURO_H

#include <ostream>

namespace EU
{
   class Euro final
   {
   public:
        explicit Euro(double value);
        virtual ~Euro() = default;

        double getValue() const;

        friend std::ostream& operator<<(std::ostream &os, const Euro &euro);

    private:
        double m_value;
    };
}

#endif // EURO_H

现在.cpp

#include "euro.h"

using namespace EU;

Euro::Euro(double value)
{
    m_value = value;
}

double Euro::getValue() const
{
    return m_value;
}

std::ostream& operator<<(std::ostream &os, const Euro &euro)
{
    os << euro.getValue() << "EUR";
    return os;
}

最后是main.cpp

And finally, the main.cpp

#include "euro.h"

#include <iostream>

using namespace EU;

int main()
{
    auto e = Euro(3.14);
    std::cout << e << std::endl;
}

但是,当我使用以下代码进行编译时:

However, when I compile this using:

g++ -std=c++11 *.cpp

它会显示以下错误:

/tmp/ccP7OKC5.o: In function `main':
main.cpp:(.text+0x35): undefined reference to `EU::operator<<(std::ostream&, EU::Euro const&)'
collect2: error: ld returned 1 exit status

我在做什么错了?

亲切的问候, 乔里斯

推荐答案

您期望using namespace EU;将所有后续代码放入namespace EU内,但不会(否则您的int main将位于命名空间也是如此!).这只是将名称空间中已经存在的东西带入范围.

You're expecting using namespace EU; to put all the subsequent code inside namespace EU, but it won't (otherwise your int main would be in the namespace too!). This just brings things already in that namespace into scope.

这意味着您在命名空间中声明了friend函数,但在全局范围内定义了一个 new 函数.调用前者将失败,因为没有定义.

It means that you're declaring the friend function inside the namespace, but defining a new function in the global scope. Calls to the former will fail because there's no definition for it.

删除using namespace,然后将namespace EU { }包裹在euro.cpp中的所有内容上.

Remove the using namespace, and wrap namespace EU { } around everything in euro.cpp.

这篇关于如何使运算符超载&lt;&lt;从名称空间中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆