c++ - 包含来自另一个文件的运算符重载

标签 c++ header operator-overloading

我想使用在另一个文件中定义的运算符,如果可能的话,还有另一个命名空间,这就是我所拥有的。

(运营商.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/

相关文章:

c++ - 是否可以在 C++ 中实现事件?

c++ - 我如何使用 Qt Creator 将一个对象的值从一个窗口获取到另一个窗口的类中?

Python POST 请求编码

c++ - 使用 gtest 模拟 boost 共享内存派生类

java - 如何在 JSP 中动态设置 header 值

ios - 如何在顶部 UICollectionView 上制作粘性标题

c++ - 为 find_if 重载函数调用运算符 ()

c++ - 模板中的运算符错误

C++ 代码迁移。方法实现一直说缺少类型

C++11 文件流