ITPub博客

首页 > > > 如何覆盖私有函数内调用的公有虚函数?

如何覆盖私有函数内调用的公有虚函数?

作者:deeply 时间:2019-11-06 14:27:11 0 删除 编辑

基类定义了私有的void run()和公有的virtual bool filter()

run()调用了filter()

在派生类中定义bool filter()

该如何通过基类的run()启动派生类的filter()?


1 #ifndef VIRBASE_H
 2 #define VIRBASE_H
 3 
 4 #include "boost/thread/thread.hpp"
 5 
 6 namespace virbase
 7 {
 8 
 9 class Vir
10 {
11 public:
12     Vir();
13     virtual ~Vir() {}
14     
15     virtual void show();
16     
17 private:
18     void run_vir();
19     boost::thread _thread;
20     
21 }; // class virbase::Vir
22 
23 } // namespace virbase
24 
25 #endif // VIRBASE_H


1 #include "virbase.h"
 2 
 3 #include <iostream>
 4 
 5 #include "boost/thread/thread.hpp"
 6 #include "boost/bind.hpp"
 7 
 8 namespace virbase
 9 {
10 
11 Vir::Vir() : _thread(boost::bind(&Vir::run_vir, this))
12 {
13 }
14 
15 void 
16 Vir::show()
17 {
18     std::cout << "virbase::Vir::show ..." << std::endl;
19 }
20 
21 void 
22 Vir::run_vir()
23 {
24     show();
25 }
26 
27 } // namespace virbase


1 #ifndef VIRDERIVED_H
 2 #define VIRDERIVED_H
 3 
 4 #include "virbase.h"
 5 
 6 namespace virderived
 7 {
 8 
 9 class Vir : public virbase::Vir
10 {
11 public:
12     explicit Vir();
13     
14     void show();
15     
16 }; // class virderived::Vir
17 
18 } // namespace virderived
19 
20 #endif // VIRDERIVED_H


1 #include "virderived.h"
 2 
 3 #include <iostream>
 4 
 5 namespace virderived
 6 {
 7 
 8 Vir::Vir() : virbase::Vir()
 9 {
10 }
11 
12 void 
13 Vir::show()
14 {
15     std::cout << "virderived::vir::show ..." << std::endl;
16 }
17 
18 } // namespace virderived


1 #include "virderived.h"
 2 
 3 int main()
 4 {
 5     using namespace virderived;
 6     
 7     Vir v;
 8     //v.run_vir(); // error
 9     
10     return 0;
11 }


如何让virderived::Vir类通过virbase::Vir::run_vir()调用virderived::Vir::show(),而不是基类virbase::Vir::show()?

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/1978/viewspace-3162138/ ,如需转载,请注明出处,否则将追究法律责任。

上一篇: sql查询拼接语句
请登录后发表评论 登录
全部评论

注册时间:2008-05-30

  • 博文量
    215
  • 访问量
    25173