首页 新闻 会员 周边

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

0
[已关闭问题] 关闭于 2012-10-31 11:01

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

在派生类中定义bool filter()
该如何通过基类的run()启动派生类的filter()?

问题补充:
virbase.h
 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
virbase.cpp
 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
virderived.h
 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
virderived.cpp
 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
test-vir.cpp
 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()?

liangxiaxu的主页 liangxiaxu | 初学一级 | 园豆:190
提问于:2012-10-24 10:51
< >
分享
所有回答(2)
1

你在基类的run方法里调用filter,如果实例是子类实例,那么调用的就是子类的filter。

水牛刀刀 | 园豆:6350 (大侠五级) | 2012-10-24 10:54
0

class BaseClass{

 private void run(){

   filter();

}

public virtual  void  filte(){}

}

 

class Extended:BaseClass{

public override void  filte(){

  base.filte();

}

}

hypernova | 园豆:276 (菜鸟二级) | 2012-10-24 19:33
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册