构造和析构函数不允许调用纯虚函数,可以先调用虚函数,里面再调用纯虚函数实现。
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;} |
c++纯虚函数在父类中调用的规避,布布扣,bubuko.com
原文:http://www.cnblogs.com/bigben0123/p/3605263.html