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

标签 c++ namespaces overloading

我在重载 << 时收到警告(尽管有效)上课 Rectangle在命名空间 Shape .请注意,我使用 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);
        };
    }

关于c++ - 为命名空间中的类重载运算符 << 时发出警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48452968/

相关文章:

html - 获取html代码时出错

c++ - 模板或函数参数作为 doxygen 中的实现细节?

c# - 将自定义命名空间导入 ASPX

Python命名空间和全局变量

c++ - 如何在 gtest 中使用带有命名空间的友元类

c++ - 使用继承和模板的数据库接口(interface)

c++ - 将变量与多个值进行比较的最有效方法?

C++:如何解决具有多个多态输入的方法调用?

java - 使用泛型作为参数重载接口(interface)中的方法