c++纯虚函数在父类中调用的规避

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

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

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

 

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

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

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
//============================================================================
// 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;
}

 

 

posted @   Bigben  阅读(1254)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
历史上的今天:
2011-03-17 新时代新潮流WebOS 【22】WebKit,鼠标引发的故事
2011-03-17 新时代新潮流WebOS 【20】WebKit的结构与解构
2011-03-17 新时代新潮流WebOS 【21】WebKit,为了布局,忙并美丽
点击右上角即可分享
微信分享提示