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
234 views
in Technique[技术] by (71.8m points)

c++ - Why the Compiler does not detect correct function signature in error?

The question is in reference to this, which was posted a little while earlier.
While the OP was happy accepting the answer which solved his problem I was a little intrigued with a detail as to why compiler gave a seemingly wrong error.

Below is a small code sample I created to demonstrate the same:

    class YourClass
    {
    };

    class YourClass2
    {
    };
    class MyClass
    {
        public:
            void doSomething(YourClass2 obj)
            {
                //Nothing more Interesting to do
            }

    };

    int main()
    {
        YourClass *ptr = new YourClass();
        MyClass obj;
        obj.doSomething(ptr);

        return 0;
    }

Compiling this with GCC(4.3.4) gives a seemingly strange error result:

prog.cpp: In function ‘int main()’:
prog.cpp:23: error: no matching function for call to ‘MyClass::doSomething(YourClass*&)’
prog.cpp:13: note: candidates are: void MyClass::doSomething(YourClass2)

So the Question is:
Why does the compiler treat the call,

obj.doSomething(ptr);

as call to a function with prototype,

MyClass::doSomething(YourClass*&)

and not

MyClass::doSomething(YourClass*)

which seems to be the obvious case.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

First, note that the expression ptr (not the variable ptr) has type YourClass *&. This is important; it's the only way reference types can work (otherwise you'd be making a reference to a copy when you do YourClass *&x = ptr, and it's also why YourClass *&x = (ptr + 1) fails). As such, the compiler starts its search for a function with MyClass::doSomething(YourClass *&).

Of course, this call can match a prototype MyClass::doSomething(YourClass *). It can also match MyClass::doSomething(const YourClass *) or many others. There's potentially dozens (or, with multiple parameters, easily hundreds or thousands) of prototypes that could potentially match this call; however, none could be found.

So the compiler gives up, and gives an error. In the error, rather listing every theoretically possible match, it cites the one prototype that most closely matches what it was originally looking for; that is, MyClass::doSomething(YourClass *&).


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

...