【问题标题】:C++ overloading operators for matrix structure矩阵结构的 C++ 重载运算符
【发布时间】:2020-03-29 02:01:55
【问题描述】:

我正在尝试使用重载运算符“+”和“=”来制作矩阵结构。

矩阵结构:

struct Matrix{
    int rows;
    int cols;
    std::vector<int> data;
    Matrix(int rows, int cols, int val);    //creates matrix row*col and fills every position with val
    Matrix(const Matrix &m);    //copy constructor
    Matrix(int rowcol = 0);    //creates matrix rowcol*rowcol filled with zeros
    Matrix & operator=(const Matrix &m);
    void printMatrix();    //prints the matrix
    ...
};

运营商:

Matrix & Matrix::operator=(const Matrix &m) //assings matrix m to the new matrix
{

}

Matrix operator+(const Matrix &a, const Matrix &b) //sums two matrices
{
    //I know how to make the algorithm for summing two matrices, however i don´t know how
    //to return the result into existing matrix
}

主要功能:

int main(){
    Matrix A(3,3,1);
    Matrix B(3,3,2);
    Matrix C(3,3,0);

    C = A + B;
    C.printMatrix();
    ...

    return 0;
}

我不知道如何让它工作。我为“=”运算符尝试了类似的方法:

Matrix & Matrix::operator=(const Matrix &m)
{
    static matrix d(m);    //using copy constructor
    return d;
}

但它不起作用。它创建了尺寸为 0x0 的新矩阵。关于如何实现它的任何建议?

【问题讨论】:

  • 我在显示的矩阵类中看不到任何需要重载复制构造函数和赋值运算符的内容。您会发现,如图所示,复制该类的一个实例会起作用,就像变魔术一样。欢迎使用 C++!
  • Some reading on Sam's point。如果零规则特别有趣,但最好了解如何以及何时应用其他两个规则,因此您应该阅读整个内容。
  • 关于尝试赋值运算符的注释。你几乎发现了Copy and Swap idiom。你出错的地方是赋值运算符应该赋值并返回this,而不是本地对象,static 或其他。

标签: c++ exception struct operator-overloading


【解决方案1】:

实现operator= 的工作方式如下:

Matrix& Matrix::operator=(const Matrix &m)
{
    this->rows = m.rows;
    this->cols = m.cols;
    this->data = m.data;

    return *this;
}

我不会接近 operator+ 所需的算法,但周围的机器也非常简单:

Matrix operator+(const Matrix &a, const Matrix &b) //sums two matrices
{
    Matrix result(<num of rows>, <num of cols>, 0);

    // do things with result here, using your algorithm, a, and b
    // e.g. result.data[?] = a.data[?] ? b.data[?]

    return result;
}

为了使这更容易,因为您的数据是一维的(很好!这很有效!),您可能希望实现一个接受 xy 的访问器维度并将索引返回到data。例如:

int& Matrix::val(const int x, const int y)
{
    assert(x < cols);
    assert(y < rows);

    return data[x + y*cols];
}

这样的结果可以是读写的,像这样:

result.val(x1, y1) = a.val(x2, y2) + b.val(x3, y3);

那些坐标和+ 只是我编造的东西,应该来自你的算法。


如果您还希望operator+= 影响现有矩阵,则:

Matrix& Matrix::operator+(const Matrix &b) //sums two matrices
{
    // do things with your object here, using your algorithm and b

    return *this;
}

return *this 用于成员操作员,虽然它是传统的,但它并不是绝对必要的,并且它允许轻松链接操作(如果您喜欢这种事情)。您可以在您的书中找到有关运算符重载的更多信息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-27
    • 1970-01-01
    • 2015-07-29
    • 2016-02-16
    相关资源
    最近更新 更多