no match for operator*

前端 未结 2 391
孤独总比滥情好
孤独总比滥情好 2020-12-18 15:39

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

2条回答
  •  执念已碎
    2020-12-18 16:14

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

提交回复
热议问题