問題描述
鑒于下面的例子,為什么我必須顯式使用語句 b->A::DoSomething()
而不僅僅是 b->DoSomething()
>?
Given the following example, why do I have to explicitly use the statement b->A::DoSomething()
rather than just b->DoSomething()
?
編譯器的重載決議不應(yīng)該弄清楚我說的是哪種方法嗎?
Shouldn't the compiler's overload resolution figure out which method I'm talking about?
我使用的是 Microsoft VS 2005.(注意:在這種情況下使用 virtual 沒有幫助.)
I'm using Microsoft VS 2005. (Note: using virtual doesn't help in this case.)
class A
{
public:
int DoSomething() {return 0;};
};
class B : public A
{
public:
int DoSomething(int x) {return 1;};
};
int main()
{
B* b = new B();
b->A::DoSomething(); //Why this?
//b->DoSomething(); //Why not this? (Gives compiler error.)
delete b;
return 0;
}
推薦答案
這兩個重載"不在同一個范圍內(nèi).默認(rèn)情況下,編譯器只考慮最小可能的名稱范圍,直到找到名稱匹配.參數(shù)匹配在之后完成.在您的情況下,這意味著編譯器會看到 B::DoSomething
.然后它嘗試匹配參數(shù)列表,但失敗了.
The two "overloads" aren't in the same scope. By default, the compiler only considers the smallest possible name scope until it finds a name match. Argument matching is done afterwards. In your case this means that the compiler sees B::DoSomething
. It then tries to match the argument list, which fails.
一種解決方案是將重載從 A
下拉到 B
的作用域:
One solution would be to pull down the overload from A
into B
's scope:
class B : public A {
public:
using A::DoSomething;
// …
}
這篇關(guān)于C++ 重載解析的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!