gex*_*ide 0 c++ methods namespaces
假设我有以下代码:
namespace x{
class X{
virtual void x(){}
}
}
namespace y{
class Y : public x::X{
void x(){}
}
}
int main(){
x::X* a = new y::Y();
a->x::X::x(); //Tries to access x::X::x non-virtually.
//Fails, since it treats the first x as the
//function name instead of the namespace
}
Run Code Online (Sandbox Code Playgroud)
如您所见,main方法的最后一行尝试静态调用类x :: X的x方法(即非虚拟).但是,这会失败,因为命名空间与方法具有相同的名称(两者都命名为x).因此,编译器将第一个x视为方法名称,然后抱怨x :: X没有任何意义.
这个问题在初看起来似乎是假设的,但它确实出现在我们的代码中:命名空间不能轻易地重命名,因为它是一个大项目的命名空间.方法名称无法更改,因为它必须遵守我们的范围之外的其他超类(库类).
那么,有没有机会以某种方式消除这种语法的歧义,以便我仍然可以非虚拟地调用方法x :: X :: x?
现在,我看到的唯一解决方案是x = X,然后使用typedef.有没有typedef的解决方案吗?
a->x::X::x(); //Tries to access x::X::x non-virtually.
//Fails, since it treats the first x as the
//function name instead of the namespace
Run Code Online (Sandbox Code Playgroud)
这实际上是对问题的一个非常清楚的描述.解决方案是删除x::部分资格.Lookup将开始Y并且将无法X在该上下文中找到,然后它将向上移动层次结构并X在X类中找到注入的名称.