简体   繁体   中英

How can I overload a C++ operator to add double plus <matrix>?

So, I'm fairly new to C++ but I have done lots of C programming. Partly as an exercise, and also partly because I don't have a matrix package that permits the fine-grained control over things that I would like, I have been writing my own matrix class mtMatrix and overloading various operators to let me write equations conveniently. I've overloaded +,-,/, and * to perform element-wise arithmetic operations, after checking that the matrices are of the same size, while full-on matrix multiplication is done by the class method Mult(). I've further overloaded +,-,/, and * to multiply matrices by scalars, so I can have a mtMatrix M and write "mtMatrix T = M * 2.0" to get a new matrix whose entries are twice as large as the old one. However, when I try to write "mtMatrix T = 2.0 * M" I run into problems, and I'm not sure how I would write the overloading for +,-, and * to accomplish this, even though what I would want is precisely the same result as if I were to type "mtMatrix T = M * 2.0." It seems that the contents of the overloading function would be identical in the two cases, but the signature of the function would be different. Can anyone point me in the right direction?

You need to create an operator associated with an lvalue as int. The operator* you have declared in your class has as lvalue 'this' therefore M*2.0 works.

In order to create an operator associated as lvalue for int you need to declare it outside the class, and if the operator has as rvalue an object of your class then you need to declare it as friend so it can access the private values.

Below is an example, where the class in not a matrix but simulates the behavior you want to accomplish.


#include <iostream>

class M 
{
    int value_;

    public:
    M(int value):value_(value){}
    int& operator()() { return this->value_; }
    int operator()() const { return this->value_; }
    int operator*(int value) { return this->value_ * value; }

    friend int operator*(int, const M&) ;  //so it can access the M private objects
};

int operator*(int value, const M& other) 
{
    return value * other.value_;
}

int main()
{
    M m0(10);
    M m1(5);
    m0() = m0() * 10;
    std::cout << m0() << std::endl;

    m0() = 10 * m1();
    std::cout << m0() << std::endl;

    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM