LinuxC/C++编程基础(34) 虚函数编程实例

一.实例1,如下:

#include <iostream>
#include <string>
class Startable;
class StartableProcess{
public:
StartableProcess(Startable& _startable):startable(_startable){
std::cout<<"Construct StartableProcess"<<std::endl;
}
void run();
private:
Startable& startable;
};
class  Startable{
public:
Startable():_process(*this){
std::cout<<"Construct Startable"<<std::endl;
}
void start(){
std::cout<<"Startable::start()"<<std::endl;
_process.run();
}
virtual void prerun(){
std::cout<<"Startable::prerun()"<<std::endl;
run();
}
virtual void run() = 0;
private:
StartableProcess_process;
};
class RTMFPServer:public Startable{
public:
RTMFPServer(){
std::cout<<"Construct RTMFPServer"<<std::endl;
}
void start(){
std::cout<<"RTMFPServer::start()"<<std::endl;
Startable::start();
}
void run(){
std::cout<<"RTMFPServer::run()"<<std::endl;
handle();
}
virtual void handle();
};
class Server:public RTMFPServer{
public:
void handle(){
std::cout<<"Server::handle()"<<std::endl;
}
};
inline void Startable::run(){
std::cout<<"Startable::run()"<<std::endl;
prerun();
}
inline void StartableProcess::run(){
std::cout<<"StartableProcess::run()"<<std::endl;
startable.prerun();
}
inline void RTMFPServer::handle(){
std::cout<<"RTMFPServer::handle()"<<std::endl;

}

int main(int argc,char** argv){
Server server;
server.start();
return 0;
}

二.实例2,如下:

#include <iostream>
#include <string>

class RTMFPManager;
class RTMFPServer{
public:
 RTMFPServer(int cores){
  std::cout<<"Construct RTMFPServer,cores="<<cores<<std::endl;
 }
 void start(){
  std::cout<<"RTMFPServer::start()"<<std::endl;
  run();
 }
 void run();
 virtual void manage(){
  std::cout<<"RTMFPManager::manage()"<<std::endl;
 }
};
class RTMFPManager{
public:
 RTMFPManager(RTMFPServer& server):_server(server){
  std::cout<<"Construct RTMFPManager"<<std::endl;
  handle();
 }
private:
 void handle() {
  std::cout<<"RTMFPManager::handle()"<<std::endl;
  _server.manage();
 }
 RTMFPServer& _server;
};
class LinyanwenServer:public RTMFPServer{
public:
 LinyanwenServer(int cores):RTMFPServer(cores){

 }
 virtual void manage(){
  std::cout<<"LinyanwenServer::manage()"<<std::endl;
 }
};
void RTMFPServer::run(){
 std::cout<<"RTMFPServer::run()"<<std::endl;
 RTMFPManager manager(*this);
}

int main()
{
 int core = 99;
 LinyanwenServer server(core);
 server.start();
 return 0;
}

 

转载请注明出处:山水间博客,http://blog.csdn.net/linyanwen99/article/details/8567685

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值