huyanjie0327 2015-06-10 01:53 采纳率: 100%
浏览 1596
已采纳

这样设计继承有什么好处?

我在阅读thrift源代码的时候,看到了类似于下面的继承设计,为什么不直接重载read, write, 而是要写个read_virt, write_virt这些函数呢?

    #include <boost/shared_ptr.hpp>
    #include <iostream>
    class Parent {
            public:
                    void read() {
                            read_virt();
                    }
                    virtual void read_virt() {

                    }
                    void write() {
                            write_virt();
                    }
                    virtual void write_virt() {

                    }
    };

    class DefaultSon : public Parent {
            public:
                    virtual void read_virt() {
                            std::cout << "DefaultSon read" << std::endl;
                    }
                    virtual void write_virt() {
                            std::cout << "DefaultSon write" << std::endl;
                    }
    };

    template <class Me, class super_ = DefaultSon>
    class VirtualParent: public super_ {
            public:
                    virtual void read_virt() {
                            return static_cast<Me *>(this)->read();
                    }
                    virtual void write_virt() {
                            return static_cast<Me *>(this)->write();
                    }
    };

    class GoodSon : public VirtualParent<GoodSon> {
            public:
                            void read() {
                                    std::cout << "GoodSon read" << std::endl;
                            }
                            void write() {
                                    std::cout << "GoodSon write" << std::endl;
                            }
    };

    class BadSon : public VirtualParent<BadSon> {
            public:
                    void read() {
                                    std::cout << "BadSon read" << std::endl;
                    }
                    void write() {
                                    std::cout << "BadSon read" << std::endl;
                    }
    };

    int main() {
            boost::shared_ptr<Parent> p(new GoodSon());
            p->read();
            p->write();

            boost::shared_ptr<Parent> q(new BadSon());
            q->read();
            q->write();
        }
  • 写回答

6条回答 默认 最新

  • threenewbee 2015-06-10 02:33
    关注

    这个是一个典型的OO设计中的技巧。我们一般管这种设计叫做NVI(Non-Virtual Interface)模式。
    http://blog.csdn.net/acloudhuang/article/details/4465084

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥15 请问读取环境变量文件失败是什么原因?
  • ¥15 在若依框架下实现人脸识别
  • ¥15 网络科学导论,网络控制
  • ¥100 安卓tv程序连接SQLSERVER2008问题
  • ¥15 利用Sentinel-2和Landsat8做一个水库的长时序NDVI的对比,为什么Snetinel-2计算的结果最小值特别小,而Lansat8就很平均
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载