C++ 的 const 重载

#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;
}

输出:

非常量版本
hello world
常量版本
hello world

基于:《C++ Primer》 P249

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

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

posted @ 2024-07-19 14:46  double64  阅读(1)  评论(0编辑  收藏  举报