运算符<<朋友的功能和模板

时间:2014-08-13 22:44:21

标签: c++ templates operators overloading friend

这是我的代码:

mov.h

#include <iostream>

template< class T>
class Movie {
public:
    Movie(T in) {
        a = in;
    }

    friend std::ostream& operator<<(std::ostream& os, const Movie<T>& movie);
private:
    T a;
};

template<class T>
std::ostream& operator<<(std::ostream& os, const Movie<T>& movie) {
    return os;
}

的main.cpp

#include "mov.h"

int main() {
    Movie<int> movie1(1);

    std::cout << movie1 << std::endl;

    return 0;
}

我尝试编译此代码,然后收到错误:

Error 1 error LNK2019: unresolved external symbol "class std::basic_ostream<char,struct std::char_traits<char> > & __cdecl operator<<(class std::basic_ostream<char,struct std::char_traits<char> > &,class Movie<int> const &)" (??6@YAAAV?$basic_ostream@DU?$char_traits@D@std@@@std@@AAV01@ABV?$Movie@H@@@Z) referenced in function _main    c:\Users\Adi\documents\visual studio 2013\Projects\bdika01\bdika01\main.obj bdika01
Error   2   error LNK1120: 1 unresolved externals   c:\users\adi\documents\visual studio 2013\Projects\bdika01\Debug\bdika01.exe    1   1   bdika01

如果我像这样内联代码,那就可以了:

mov.h

 #include <iostream>

 template<class T>
 class Movie {
 public:
     Movie(T in) {
         a = in;
    }

    friend std::ostream& operator<<(std::ostream& os, const Movie<T>& movie){
        return os;
    }
private:
    T a;
};

如果我想将定义和声明分开,我该怎么办?

感谢。

1 个答案:

答案 0 :(得分:6)

template <typename T> class Movie;

template<class T>
std::ostream& operator<<(std::ostream& os, const Movie<T>& movie);

template< class T>
class Movie {
  friend std::ostream& operator<< <T>(std::ostream& os, const Movie<T>& movie);
};

template<class T>
std::ostream& operator<<(std::ostream& os, const Movie<T>& movie){
    return os;
}

在原始代码中,您将成为非模板函数,恰好将Movie<>的正确实例化作为参数。因此,每次实例化Movie<T>时,在封闭的命名空间范围内声明(但未定义)相应的非模板operator<<friend声明这种方式很奇怪。

此外,您声明并定义了一个名为operator<<的函数模板(它不是Movie的任何实例化的朋友)。但是,重载决策更喜欢非模板,其他条件相同。