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

时间:2014-04-12 19:45:09

标签: c++ operator-overloading

为编写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";
}

1 个答案:

答案 0 :(得分:0)

您需要将所有模板化的类函数定义移动到头文件中,或者将explicitly specialize模板移动到.cpp文件中。