简介: CSDN博客专家,专注Android/Linux系统,分享多mic语音方案、音视频、编解码等技术,与大家一起成长!
优质专栏:Audio工程师进阶系列【原创干货持续更新中……】🚀
人生格言: 人生从来没有捷径,只有行动才是治疗恐惧和懒惰的唯一良药.
1.前言
本篇目的:理解模板类重写基类构造函数,子类必须重写。
2.应用实例
v1.0 模板类单个参数
#include<iostream>
#include <typeinfo>
using namespace std;
template<typename SERVICE>
class BaseA{
public:
//explicit:当基类重写了构造函数函数,子类必须继承重写,否则与基类构造函数的类型不一致,导致报错.
BaseA(SERVICE *ptr) : mPtr(ptr){
printf("xxx--------->line = %d, type = %s, name = %s\n",__LINE__,typeid(SERVICE).name(),SERVICE::getName());
}
SERVICE *get(){
printf("xxx--------->%s(), line = %d\n",__FUNCTION__,__LINE__);
return mPtr;
}
void test(){
printf("xxx--------->%s(), line = %d\n",__FUNCTION__,__LINE__);
}
//virtual void tt_01() = 0;
SERVICE *mPtr;
};
class Parent: public BaseA<Parent>{
public:
Parent() : BaseA<Parent>(this) {}
static const char *getName() { return "media.audio"; }
int value = 100;
virtual void tt_01(){
printf("xxx--------->%s(), line = %d\n",__FUNCTION__,__LINE__);
}
};
class Derived: public Parent{
public:
int count = 200;
virtual void tt_01(){
printf("xxx--------->%s(), line = %d\n",__FUNCTION__,__LINE__);
}
};
int main(){
//v1.0
Parent *dr = new Derived;
dr->get();
dr->tt_01();
//v2.0
Parent *pt = new Parent;
pt->tt_01();
}
v2.0 模板类两个参数
#include<iostream>
#include <typeinfo>
using namespace std;
template<typename SERVICE>
class BaseA{
public:
//当基类重写了构造函数函数,子类必须继承重写,否则与基类构造函数的类型不一致,导致报错.
//模板函数提供了两个参数.
BaseA(SERVICE *ptr, int c) : mPtr(ptr),m_c(c){
printf("xxx--------->line = %d, type = %s, name = %s\n",__LINE__,typeid(SERVICE).name(),SERVICE::getName());
}
SERVICE *get(){
printf("xxx--------->%s(), line = %d\n",__FUNCTION__,__LINE__);
return mPtr;
}
void test(){
printf("xxx--------->%s(), line = %d\n",__FUNCTION__,__LINE__);
}
virtual void tt_01() = 0;
SERVICE *mPtr;
int m_c;
};
class Parent: public BaseA<Parent>{
public:
Parent(int c) : BaseA<Parent>(this, c) {}
static const char *getName() { return "media.audio"; }
int value = 100;
virtual void tt_01(){
printf("xxx--------->%s(), line = %d\n",__FUNCTION__,__LINE__);
}
};
class Derived: public Parent{
public:
Derived(int c) : Parent(c) {}
int count = 200;
virtual void tt_01(){
printf("xxx--------->%s(), line = %d\n",__FUNCTION__,__LINE__);
}
};
int main(){
//v1.0
Parent *dr = new Derived(2);
dr->get();
dr->tt_01();
//v2.0
Parent *pt = new Parent(1);
pt->tt_01();
}
3.总结
1.当基类重写了构造函数函数,子类必须继承重写,否则与基类构造函数的类型不一致,导致报错.