#include <iostream>
#include <string>

namespace
{
    class A
    {
    public:
        const A& get_self() const
        {
            std::cout << "常量版本" << std::endl;
            return *this;
        }

        A& get_self()
        {
            std::cout << "非常量版本" << std::endl;
            return *this;
        }

        void set_hi(std::string h)
        {
            hi = h;
        }
        void show_hi() const
        {
            std::cout << hi << std::endl;
        }
    private:
        std::string hi{ "hello world" };
    };
}

int main()
{
    A a;
    a.get_self().show_hi();

    const A aa;
    aa.get_self().show_hi();
    //aa.set_hi("good morning"); // 非常量版本的函数对于常量对象不可用

    return 0;
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.

输出:

非常量版本
hello world
常量版本
hello world
  • 1.
  • 2.
  • 3.
  • 4.

基于:《C++ Primer》 P249

常量版本的函数对于常量对象是不可用,所以我们只能在一个常量对象上调用 const 成员函数。另一方面,虽然可以在常量对象上调用常量版本和非常量版本,但显然此时非常量版本是一个更好的匹配。

在实践中,设计良好的C++代码常常包含大量类似的小函数,通过调用这些函数,可以完成一组其他函数“实际”工作。