C++ 类外运算符实现解析为 `namespace::operator<<` 而不是 `operator<<`

标签 c++ namespaces operator-overloading header-files

所以我在写 operator<<类的重载如下:

#test.hh
#pragma once
#include<iostream>
namespace ns {
    struct test {
        double d;
        test(double x): d(x) {}
        friend std::ostream& operator<<(std::ostream&, const test&);
    };
}
#test.cc
#include"./test.hh"
std::ostream& operator<<(std::ostream& os, const ns::test& a) {
    os << a.d;
    return os;
}
使用以下主要测试:
#main.cc
#include"./test.hh"
#include<iostream>
int main() {
    ns::test a(12);
    std::cout << a << std::endl;
    return 0;
}
当用 g++ test.cc main.cc 编译时返回错误:
/usr/sbin/ld: /tmp/cc6Rs93V.o: in function `main':                                                      
main.cc:(.text+0x41): undefined reference to `ns::operator<<(std::ostream&, ns::test const&)'           
collect2: error: ld returned 1 exit status
显然,编译器将该函数解析为 ns::operator<<什么时候应该打电话operator<< .我知道 C++ 会在参数的命名空间中找到函数,但是我是否错误地实现了运算符重载? Answers like this似乎与我有相同的实现,唯一的区别是它们都写在 header.xml 中。
我做错了哪一部分?我怎么能解决这样的问题?

最佳答案

对于这样的情况,这是我的解决方案:

#include<iostream>

namespace ns 
{
    struct test 
    {
        double d;
        test(double x) : d(x) {}
        friend std::ostream& operator<<(std::ostream&, const test&);
    };

    std::ostream& operator<<(std::ostream& os, const ns::test& a) {
        os << a.d;
        return os;
    }
}

int main() 
{
    ns::test a(12);
    std::cout << a << std::endl;
    return 0;
}

关于C++ 类外运算符实现解析为 `namespace::operator<<` 而不是 `operator<<`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69233171/

相关文章:

silverlight - 使用命名空间 Silverlight/XAML 的具体示例有哪些?

namespaces - Mediawiki 自定义命名空间 ID 更改

C++:运算符和模板

c++ - 此代码对于重载比较运算符是否正确?

c++ - MSVC : "use of class template requires template argument list" inside STL containers

c++ - 未定义的方法引用

ruby-on-rails - Rails 正在寻找错误目录中的部分内容

c++ - 运算符重载示例不清楚

c++ - iso c++ 禁止声明没有类型的泛型

c++ - 为什么 C++ 认为 8^1/3 = 1?