不同命名空间中的相同函数名称

时间:2015-07-21 06:34:24

标签: c++

假设我有不同的命名空间 像apple namespace和orange namespace一样,但两个命名空间都包含一个名为myfunction()的函数。

当我在main()中调用myfunction()时会发生什么?

2 个答案:

答案 0 :(得分:22)

这正是引入名称空间的原因。

在您的main()全局命名空间中,您可以选择必须调用myfunctions

int main()
{
     apple::myfunction(); // call the version into the apple namespace
     orange::myfunction(); // call the orange one
     myfunction(); // error: there is no using declaration / directive
}

如果使用指令using namespace apple)或使用声明using apple::myfunction),则主要的最后一行会有称为命名空间apple内的版本。如果myfunction的两个版本都在范围内,则最后一行会再次产生错误,因为在这种情况下,您必须指定必须调用哪个函数。

答案 1 :(得分:5)

请考虑以下示例。

namespace Gandalf{

    namespace Frodo{
         bool static hasMyPrecious(){ // _ZN7Gandalf5FrodoL13hasMyPreciousEv
            return true;
        }
    };

    bool static hasMyPrecious(){ // _ZN7GandalfL13hasMyPreciousEv
        return true;
    }
};

namespace Sauron{
    bool static hasMyPrecious(){ // _ZN5SauronL13hasMyPreciousEv
        return true;
    }
};

bool hasMyPrecious(){ // _Z13hasMyPreciousv
    return true;
}

int main()
{
    if( Gandalf::Frodo::hasMyPrecious() || // _ZN7Gandalf5FrodoL13hasMyPreciousEv
        Gandalf::hasMyPrecious()        ||  // _ZN7GandalfL13hasMyPreciousEv
        Sauron::hasMyPrecious()          || // _ZN5SauronL13hasMyPreciousEv
        hasMyPrecious()) // _Z13hasMyPreciousv
        return 0;

    return 1;
}

根据函数声明的命名空间,编译器生成每个函数的唯一标识,称为Mangled Name,它只是命名空间作用域的编码,函数名称,返回类型和实际参数。看评论。当您创建对此函数的调用时,每个函数调用都会查找相同的错位签名,如果找不到则编译器报告错误。

如果您对内部工作感兴趣,请尝试使用clang -emit-llvm -S -c main.cpp -o main.ll进行试验。

相关问题