zoukankan      html  css  js  c++  java
  • c++纯虚函数在父类中调用的规避

    构造和析构函数不允许调用纯虚函数,可以先调用虚函数,里面再调用纯虚函数实现。

    class Base{
    public:
        virtual void foo()=0;
        Base() { call_foo();}
        void call_foo() { foo(); }

    };
     
    class Derived: Base{
        void foo() {  }
    };
     
    int main() {
        Derived d;
    }

    在父类中定义纯虚函数,实现工厂生产。子类再实现。可以用虚函数里面调用纯虚函数实现。

    父类实现了线程,子类实现方法即可示例:

    //============================================================================
    // Name        : mytestcpp.cpp
    // Author      :
    // Version     :
    // Copyright   : Your copyright notice
    // Description : Hello World in C++, Ansi-style
    //============================================================================
    
    #include <iostream>
    
    using namespace std;
    
    #include <string>
    #include <iostream>
    #include "pthread.h"
    using namespace std;
    
    class ITestComponent {
    public:
    
    	virtual void* thread_run(void* para)=0;
    
    	virtual void* thread_run_tmp(void* para) {
    		thread_run(para);
    	}
    	;
    	virtual void start() {
    		typedef void* (*FUNC)(void*); //定义FUNC类型是一个指向函数的指针,该函数参数为void*,返回值为void*
    		FUNC callback = (FUNC) &ITestComponent::thread_run_tmp; //强制转换func()的类型
    
    		int rc;
    		pthread_t thread_instance;
    		pthread_attr_t attr; // Thread attribute
    
    		pthread_attr_init(&attr);
    		pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);
    		pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
    
    		rc = pthread_create(&thread_instance, &attr, callback, this);
    		if (rc) {
    			cout << "thread_instance thread ERROR; return code is  " << rc << endl;
    		}
    		pthread_attr_destroy(&attr);
    
    	}
    
    protected:
    };
    
    class HardwareMeter: public ITestComponent {
    public:
    	void* thread_run(void *para) {
    		while (1) {
    			cout << "HardwareMeter " << " start." << endl;
    		}
    
    	}
    };
    
    int main() {
    	cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!!
    	HardwareMeter hm;
    	hm.start();
    	cin >> i;
    	return 0;
    }
    
  • 相关阅读:
    go mod 安装依赖 unkown revision问题解决
    K8S学习笔记
    TCP time_wait close_wait问题(可能是全网最清楚的例子)
    认识beanstalkd
    【线上问题系列】DB字段类型变更导致核心服务不可用
    mysql 类型自动化转换问题
    curl 用法
    requests访问https站点证书告警问题
    博客目录
    工作随笔——elasticsearch数据冷热分离、数据冷备
  • 原文地址:https://www.cnblogs.com/bigben0123/p/3605263.html
Copyright © 2011-2022 走看看