简体   繁体   中英

C++ Operator Overload and Inheritance

So I have a generic Matrix class that I created which has the following operator overload:

class Matrix
{
public:
    Matrix() {}
    Matrix(int i, int j, int k) {}
    Matrix operator*(const Matrix &right)
    {
    }
};

I also have a Matrix2 class that inherits from my Matrix class.

class Matrix2 : public Matrix
{
};

When I try to multiply two Matrix2 objects together I get a compiler error stating:

'there is no operator found which takes a left hand operand of type Matrix2 (or there is no accessible conversion)'

Why is this and how can I properly implement operator overloads with inheritance?

EDIT:

As pointed out my problem was partially because of the "most vexing parse". Now my problem, I believe, strictly has to do with the operator overload and inheritance.

I can multiply two Matrix objects just fine, but I cannot multiply two Matrix2 objects together.

Matrix2 i;
Matrix2 m;
Matrix result = m * i;

The error message:

error C2678: binary '*' : no operator found which takes a left-hand operand of type 'Matrix2' (or there is no acceptable conversion).

You are biting the Most Vexing Parse. It is a syntactic error leading to the declaration of functions rather than objects.

The problem isn't with the overloaded operator, it's with the variables you defined, you're probably thinking that m1 and m2 are of type Matrix but what they actually are is functions returning Matrix (with no parameters). Try removing the parentheses in the declaration and see if things look better.

This is the Most Vexing Parse that @DeadMG is refering to in his answer.

Check out this article on operator overloading, it explains things very well.

As @silvesthu explains, it might be better to implement the multiplication operator as a static function taking 2 arguments and returning a new Matrix object. If you need to modify your class in some way such as using the *= operator, you can implement this in terms of the static function.

Update

Compiling the following code works for me;

class Matrix
{
public:
    Matrix() {}
    Matrix(int i, int j, int k) {}
    Matrix operator*(const Matrix &right)
    {
        return Matrix();
    }
};

class Matrix2 : public Matrix
{
};


int _tmain(int argc, _TCHAR* argv[])
{
    Matrix2 a, b;
    Matrix c = a * b;
    return 0;
}

Showing that two Matrix2 objects can indeed be multiplied together. I am not sure why you are getting any problems at all.

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