Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm reading Effective C++ (Scott Meyers), and getting the error " no match for operator* " when trying to compile following code from this book:

rational.h

class rational
{
    private:
        int num;
        int den;
    public:
        rational(int n = 0, int d = 1);
        int getNum() const {return num;}
        int getDen() const {return den;}
};

rational.cpp

#include "rational.h"

rational::rational(int n,
                    int d)
    :num(n),
     den(d)
{}

const rational operator*(const rational &lhs, 
                         const rational &rhs)
{
    return  rational( lhs.getNum()*rhs.getNum(),
                      lhs.getDen()*rhs.getDen() );
}

main.cpp

#include "rational.h"
int main()
{
    rational r1(1,2);
    rational r2;
    r2 = 2*r1;
    r2 = r1*3;
    return 0;
}

Can someone explain why this is happening ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
251 views
Welcome To Ask or Share your Answers For Others

1 Answer

You forgot to tell your users about the existence of your operator:

rational.h

...
const rational operator*(const rational &lhs, 
                         const rational &rhs);
...

Generally, in C as well as in C++, we talk about "definitions" and "declaration". Declarations are annotations to make something visible to someone else, but in itself they do nothing. Definitions are the entititiess that actually do something:

int foo();              // <- we call it "declaration"
int foo() { return 0; } // <- we call it foo's "definition"

In your code, there is no declaration of operator* visible in main.cpp, so you need to provide one somewhere (ideally in your rational's header).

As a style advice: In almost all cases, if a constructor takes builtin types, you want to make it explicit:

explicit rational (int, int);

This prevents sometimes subtle bugs because (in your case) rationals might be unintentionally created (see Automatic Conversions).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...