C ++函数(附加费和常数)

时间:2016-07-06 15:34:46

标签: c++ c++11

我有以下代码

//*********************************************
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");

将执行哪个脚本?

2 个答案:

答案 0 :(得分:4)

让我们展开

section("database_path");

完全等同于

this->section("database_path");

如果thisconst(即包含上述内容的方法标记为const),则会调用const的{​​{1}}版本。否则,将调用非section版本。

答案 1 :(得分: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-&gt; f = f()

c3.f = f()const

c4.f = f()const

c5.f = f()const

c6.f = f()