2016-07-06 16 views
0

我有以下代碼C++函數(收費和常量)

//********************************************* 
Section& 
BasicConfig::section (std::string const& name) 
{ 
    return map_[name]; 
} 
//************************************************* 
Section const& 
BasicConfig::section (std::string const& name) const 
{ 
    static Section none(""); 
    auto const iter = map_.find (name); 
    if (iter == map_.end()) 
     return none; 
    return iter->second; 
} 

如果我寫:section("database_path");

哪個腳本會被執行?

+6

你在'const'上調用它的對象是不是? – NathanOliver

+4

爲什麼不嘗試呢? – Igor

+0

@Igor:他不會從簡單的嘗試中學到很多東西。 –

回答

4

讓我們擴展

section("database_path");

到完全等價

this->section("database_path");

如果thisconst(即含有上述的方法被標記const),則const版本的section被調用。否則調用非const版本。

1

這取決於上下文。看這個:

#include <iostream> 
#include <string> 

std::string gs; 

class C 
{ 
    public: 
     std::string& f(std::string const & s) { gs = "f()"; return gs; } 
     std::string& f(std::string const & s) const { gs = "f() const"; return gs; } 

     std::string a() const 
     { 
      return f("s"); 
     } 

     std::string b() 
     { 
      return f("s"); 
     } 

}; 

int main() 
{ 
    C c1; 
    C *c2 = &c1; 
    const C c3; 
    const C& c4 = c1; 
    const C* c5 = &c1; 
    C* const c6 = &c1; 


    std::cout << "c1.a = " << c1.a() << std::endl; 
    std::cout << "c1.b = " << c1.b() << std::endl; 
    std::cout << "c1.f = " << c1.f("s") << std::endl; 
    std::cout << "c2->f = " << c2->f("s") << std::endl; 
    std::cout << "c3.f = " << c3.f("s") << std::endl; 
    std::cout << "c4.f = " << c4.f("s") << std::endl; 
    std::cout << "c5.f = " << c5->f("s") << std::endl; 
    std::cout << "c6.f = " << c6->f("s") << std::endl; 


    return 0; 
} 

輸出:

c1.a = F()const的

c1.b = F()

c1.f = F()

c2-> f = f()

c3.f = F()const的

c4.f = F()const的

c5.f = F()const的

c6.f = F()