2013-10-21 13 views
2

可有人請解釋什麼規則確定編譯器調用函數對象f下方而不是函數f的?編譯器選擇了仿函數同名

#include <iostream> 

struct A { 
    void operator()() { std::cout << "functor" << std::endl; } 
}; 

void f() { std::cout << "function" << std::endl; } 

int main() 
{ 
    A f; 
    f(); // Output: functor 
} 

A::operator()()f()不超載,所以我的猜測是這種情況發生重載決議之外。

回答

5

這是由於名稱隱藏。當你聲明f變量時,它隱藏了f函數。在該範圍內使用名稱f的任何使用將引用局部變量而不是函數。

如果你想調用的函數f,那麼你可以使用scope resolution operator

#include <iostream> 

struct A { 
    void operator()() { std::cout << "functor" << std::endl; } 
}; 

void f() { std::cout << "function" << std::endl; } 

int main() 
{ 
    A f; 
    ::f(); // Output: function 
}