我想使用在另一个文件中定义的运算符,如果可能的话,还有另一个命名空间,这就是我所拥有的。
(运营商.hpp)
#ifndef __OPERATORS__HPP__
#define __OPERATORS__HPP__
#include "proto_handler.hpp"
#include <iostream>
namespace apius {
namespace support {
namespace operators{
std::istream& operator>>(std::istream& in,
inventory::proto::item& item);
}
}
}
(操作.cpp)
#include "operators.hpp"
namespace apius {
namespace support {
namespace operators{
std::istream& operator>>(std::istream& in,
inventory::proto::item& item){
//code here
}
}
}
}
(另一个文件.cpp)
#include "operators.hpp"
extern std::istream& operator>>(std::istream& in,
inventory::proto::item& item);
void test(){
inventory::proto::item new_item;
std::cin>>new_item;
}
我在包含 std::cin 的行中得到对运算符的 undefined reference
我该怎么做才能使这项工作成功?
最佳答案
基本上链接器很难找到这样的符号,因为没有。由于 C++ 名称重整,您将在目标文件的符号表中得到类似 __ZN5apius7support9operatorsrsERNSt3__113basic_istream... 的内容。请注意,命名空间部分也在那里。但是您是在告诉全局 namespace 中有这样的运算符。正如阿德里安正确地注意到你可以简单地添加
using namespace apius::support::operators;
此外,我更喜欢做的是在类中声明一个友元运算符,然后你不需要任何使用。
关于c++ - 包含来自另一个文件的运算符重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58768948/