C ++重载分辨率 [英] C++ overload resolution
问题描述
给定以下示例,为什么我必须显式使用语句 b-> A :: DoSomething()
,而不是 b - > DoSomething()
?
编译器的重载分辨率不应该决定我正在讨论的方法吗?
我使用的是Microsoft VS 2005.(注意:在这种情况下使用virtual不起作用。)
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(); //为什么这个?
// b-> DoSomething(); //为什么不是这个? (给出编译器错误。)
delete b;
return 0;
}
在同一范围内。默认情况下,编译器只考虑最小可能的名称范围,直到找到名称匹配。随后进行参数匹配。在你的情况下,这意味着编译器看到 B :: DoSomething
。
一个解决方案是从 A下拉过载
into B
的范围:
public:
using A :: DoSomething;
// ...
}
Given the following example, why do I have to explicitly use the statement b->A::DoSomething()
rather than just b->DoSomething()
?
Shouldn't the compiler's overload resolution figure out which method I'm talking about?
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;
}
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.
One solution would be to pull down the overload from A
into B
's scope:
class B : public A {
public:
using A::DoSomething;
// …
}
这篇关于C ++重载分辨率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!