重载运算符时的警告<<对于名称空间

时间:2018-01-25 22:31:20

标签: c++ namespaces overloading

当在名称空间<<中为类Rectangle重载Shape时,我收到警告(但它有效)。请注意,我使用Clion生成了重载但仍然收到警告。

Rectangle.h

#include <ostream>

namespace Shape {

    class Rectangle {
    public:
        friend std::ostream &operator<<(std::ostream &os, const Rectangle &rectangle);
    };
}

Rectangle.cpp

#include "Rectangle.h"

using namespace Shape;

std::ostream& Shape::operator<<(std::ostream &os, const Rectangle &rectangle) {
    os << "rectangle";
    return os;
}

警告:

warning: 'std::ostream& Shape::operator<<(std::ostream&, const Shape::Rectangle&)' has not been declared within Shape
 std::ostream& Shape::operator<<(std::ostream &os, const Rectangle &rectangle) {
               ^~~~~

note: only here as a friend
         friend std::ostream &operator<<(std::ostream &os, const Rectangle &rectangle);
                              ^~~~~~~~

如何妥善处理,以免发出警告? 谢谢

2 个答案:

答案 0 :(得分:1)

我找到了它!

您必须在命名空间内定义重载方法,而不是在类中。

#include <ostream>

    namespace Shape {

        class Rectangle {
        };
        std::ostream &operator<<(std::ostream &os, const Rectangle &rectangle);
    }

不是这样的:

#include <ostream>

    namespace Shape {

        class Rectangle {
        public:
            friend std::ostream &operator<<(std::ostream &os, const Rectangle &rectangle);
        };
    }

答案 1 :(得分:0)

只需删除tuple

Shape::

编辑:您还必须在std::ostream& operator<<(std::ostream &os, const Rectangle &rectangle) { os << "rectangle"; return os; } 中封装重载的函数定义。

或者,您可以在namespace Shape {...}内声明operator<<(),但在namespace Shape之外声明:

Rectangle