【问题标题】:operator << overloading in c++运算符 << C++ 中的重载
【发布时间】:2015-03-07 05:13:47
【问题描述】:

我编写了这段代码

声明:

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;
}

我收到此错误:

错误 1 ​​错误 LNK2019:无法解析的外部符号“类 std::basic_ostream > & __cdecl 运算符

&,类矩阵)" (??6@YAAAV?$basic_ostream@DU?$char_traits@D@std@@@std@@AAV01@V?$Matrix@H@@@Z) 在函数 _main C:\Users\igor\documents\visual studio 中引用 2013\Projects\matrix\matrix\Source.obj 矩阵

我尝试在没有朋友的情况下编写它,但出现了不同的错误。
我做错了什么?

【问题讨论】:

  • main.cpp 中的#included 是.h 文件中的定义吗?发布MCVE 将非常有用。
  • 我不知道这是否与您的问题有关(我认为不是),但您仍然应该让您的函数采用 const Matrix&lt;T&gt;&amp; 而不是 Matrix&lt;T&gt;
  • @IgorGumush 直接在头文件中定义模板化运算符,而不是在 .cpp 文件中
  • 由于这是一个模板,operator&lt;&lt;定义必须是#included 和标题。这是你做的吗?

标签: c++ matrix operator-overloading


【解决方案1】:

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 会找到它,这就是您想要的一切。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-16
    • 2011-08-23
    • 2011-03-25
    相关资源
    最近更新 更多