为什么运算符重载不能正常工作

Why operator overloading doesn't working fine

本文关键字:工作 常工作 运算符 重载 不能 为什么      更新时间:2023-10-16

为了教育目标,为sys/socket编写类包装器。

https://github.com/nkt/cpp-socket/blob/master/src/Socket.cpp#L94-这就是方法。https://github.com/nkt/cpp-socket/blob/master/chat/main.cpp#L17-这是用法。

因此,XCode抛出一个错误:

Undefined symbols for architecture x86_64:
  "Socket& operator<<<char const [16]>(Socket&, char const (&) [16])", referenced from:
      _main in main.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

尽管此代码编译和工作良好:

#include <iostream>
#include <string>
class test
{
public:
    void send(std::string str);
    template <class T>
    friend test &operator <<(test &tst, T &message);
};
void test::send(std::string str)
{
    std::cout << str;
}
template <class T>
test &operator <<(test &tst, T &message)
{
    tst.send(std::string(message));
    return tst;
}
int main()
{
    test t;
    t << "hello world!n";
}

您要么需要将所有模板化的类函数定义移动到头文件中,要么在.cpp文件中显式地专门化模板。