为命名空间中的类重载运算符<<时发出警告

warning when overloading operator << for a class within a namespace

本文关键字:lt 警告 运算符 命名空间 重载      更新时间:2023-10-16

当命名空间ShapeRectangle类重载<<时,我会收到警告(尽管它有效(。请注意,我使用 Clion 生成了重载,但仍然收到警告。

矩形.h

#include <ostream>
namespace Shape {
    class Rectangle {
    public:
        friend std::ostream &operator<<(std::ostream &os, const 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);
                              ^~~~~~~~

如何正确执行此操作,以免发出警告?谢谢

我找到了!

您必须在命名空间中定义重载方法

,而不是在类中定义重载方法。

#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);
        };
    }

只需删除Shape::

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

编辑:您还必须将重载的函数定义封装在namespace Shape {...}中。


或者,您可以在 namespace Shape 内声明operator<<(),但在Rectangle外部声明:

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