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

时间:2023-03-08 22:11:06

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

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;
}