【问题标题】:Operator << in C++, "no operator found which takes right hand-operator" and "already has a body" error运算符 << 在 C++ 中,“找不到使用右手运算符的运算符”和“已经有正文”错误
【发布时间】:2021-10-13 19:54:20
【问题描述】:

我有一些代码应该重载运算符

#pragma once
#include <iostream>

using std::cout;
using std::endl;
using std::ostream;

template <int N=1, int M=1, class T = int>
class Matrix {
    int rows;
    int cols;
    T matrix[N][M];
public:

Matrix(T matrixVal = 0) :rows(N), cols(M) {
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            this->matrix[i][j] = matrixVal;
        }
    }
}

int getRows() { return rows; }
int getCols() { return cols; }
T** getMatrix() { return matrix; }

friend ostream& operator<<(ostream& out, const Matrix<>& mat) {
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            out << this->matrix[i][j];
            out << " ";
        }
        out << endl;
    }
    return out;
}

但是当我添加它时,我得到了这些错误:

错误 C2084 函数 'std::ostream &Matrix::operator &)' 已经有一个主体

错误 C2679 二进制 '' 类型的操作数(或没有可接受的转换)

Error (active) E0349 no operator "

这里是主要代码:

#include "matrix.h"

template <int row, int col, typename T>
void printDiag(Matrix<row, col, T>& mat) {
    int number;
    T* diag = mat.getDiag(number);
    for (int i = 0; i < number; i++)
    {
    std::cout << diag[i] << " ";
   }
   std::cout << std::endl;
   delete[] diag;
}

int main() {

//freopen("output_matrix.txt", "w", stdout);

Matrix<4, 4> mat;
std::cout << mat << std::endl;

Matrix<4, 4> identity(1);
std::cout << identity << std::endl;

任何帮助将不胜感激(:

【问题讨论】:

  • 失败是什么?
  • template &lt;int N, int M, class T&gt; friend ostream&amp; operator&lt;&lt;(ostream&amp; out, const Matrix&lt;N,M,T&gt;&amp; mat) 而不是?
  • 我尝试了@m88 的建议,但它似乎不起作用,弹出更多错误,例如 Error C2568 '
  • @user253751 我更新了问题,对此感到抱歉
  • @LeonGurin 好友功能不是会员。你不能使用this。在这种情况下,您不需要模板,但您希望在函数声明中指定 Matrix&lt;N,M,T&gt;。你也不能使用rows/cols使用mat.rowsmat.cols

标签: c++ operator-overloading operators


【解决方案1】:

这有几个问题。首先在声明中你必须指定模板参数。由于整个类都是模板化的,所以之前不需要显式添加另一个template,但需要Matrix&lt;N,M,T&gt;

第二个问题是您将friend std::ostream&amp; operator&lt;&lt;(...) 视为成员函数(使用成员变量和this)。不是这种情况。你可能会在类中声明它,但它绝对不是类的一部分。在你使用this-&gt; 的地方使用mat.,而你只使用rows/cols 的地方使用mat.rows/mat.cols

我也不得不稍微修改一下构造函数,但我仍然不知道它为什么抱怨。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-26
    • 1970-01-01
    • 1970-01-01
    • 2016-02-19
    • 2012-02-29
    • 1970-01-01
    • 2012-02-20
    相关资源
    最近更新 更多