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

Categories

0 votes
260 views
in Technique[技术] by (71.8m points)

c++ - no match for operator*

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

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

1 Answer

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...