运算符 << 在 C++ 中重载

operator << overloading in c++

我制作了这段代码

声明:

template <class T>
class Matrix
{
    std::vector< std::vector<T> > mat;
    size_t rows , cols;
public:

    Matrix<T>();
    Matrix<T>(const std::string);
    Matrix(const size_t r, const size_t c, const std::vector<T> v);
    Matrix<T> operator=(const Matrix<T> &other);

    friend std::ostream& operator<<(std::ostream &os , Matrix<T> m);
};

函数:

template <class T>
std::ostream& operator<<(std::ostream &os , Matrix<T> m){

    for (size_t i = 0; i < m.rows; i++)
    {
        for (size_t j = 0; j < m.cols; j++)
        {
            os << m.mat[i][j] << " ";
        }
        os << std::endl;
    }
    return os;
}

主要 :

int main(){
    std::vector<int> v(9);
    v[0] = 1;
    v[1] = 2;
    v[2] = 3;
    v[3] = 4;
    v[4] = 5;
    v[5] = 6;
    v[6] = 7;
    v[7] = 8;
    v[8] = 9;
    Matrix<int> m = Matrix<int>(2, 3, v);
    std::cout << m;
}

我收到这个错误:

Error 1 error LNK2019: unresolved external symbol "class std::basic_ostream > & __cdecl operator<<(class std::basic_ostream

&,class Matrix)" (??6@YAAAV?$basic_ostream@DU?$char_traits@D@std@@@std@@AAV01@V?$Matrix@H@@@Z) referenced in function _main C:\Users\igor\documents\visual studio 2013\Projects\matrix\matrix\Source.obj matrix

我试着在没有朋友的情况下写它,但得到了一个不同的错误。
我做错了什么?

You must implement a template in the header-file, not only declare it there.
当然,除非您可以显式实例化所有需要的特化。

无论如何,考虑一下 defining your friend inline:

template <class T>
class Matrix
{
    //...
    friend std::ostream& operator<<(std::ostream &os , Matrix<T> m) {
        // do things
        return os;
    }
};

除非您也在包含范围中声明它,否则您将无法显式调用它,但 ADL 会找到它,这就是您想要的。