所以我在写 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/