简介: CSDN博客专家,专注Android/Linux系统,分享多mic语音方案、音视频、编解码等技术,与大家一起成长!
优质专栏:Audio工程师进阶系列【原创干货持续更新中……】🚀
人生格言: 人生从来没有捷径,只有行动才是治疗恐惧和懒惰的唯一良药.
1.前言
本篇目的:理解模板类指向子类对象应用。
2.应用实例
<1>.v1.0
#include<iostream>
using namespace std;
template<typename SERVICE>
class BaseA{
public:
BaseA(){
//printf("xxx--------->%s(), line = %d, i = %s\n",__FUNCTION__,__LINE__,SERVICE::getServiceName());
}
virtual void test(int i) = 0;//纯虚函数,子类必须实现.
};
class Parent{
public:
Parent(){
printf("xxx--------->%s(), line = %d\n",__FUNCTION__,__LINE__);
}
};
//Derived继承自类模板BaseA<任意类型>.将子类的类型传参给模板类,在模板类可以调用子类Derived的getServiceName()和value
class Derived: public BaseA<Derived>{
friend class BaseA<Derived>;
public:
void test(int i){
printf("xxx--------->%s(), line = %d, i = %d\n",__FUNCTION__,__LINE__,i);
}
static const char *getServiceName() { return "media.audio_policy"; }
int value = 100;
};
int main(){
//1.子类指向子类对象
Derived *dr = new Derived();
dr->test(777);
printf("xxx--------->%s(), line = %d, value = %d\n",__FUNCTION__,__LINE__,dr->value);
//2.父类指向子类对象
BaseA<Derived> *b = new Derived;
b->test(999);
//printf("xxx--------->%s(), line = %d, value = %d\n",__FUNCTION__,__LINE__,b->value);//error
}
<2>.v2.0
#include<iostream>
using namespace std;
template<typename SERVICE>
class BaseA{
public:
BaseA(){
printf("xxx--------->%s(), line = %d, i = %s\n",__FUNCTION__,__LINE__,SERVICE::getName());
}
virtual void test(int i) = 0;//纯虚函数,子类必须实现.
};
class Parent{
public:
Parent(){
printf("xxx--------->%s(), line = %d\n",__FUNCTION__,__LINE__);
}
static const char *getName() { return "Hello Test."; }
};
class Derived: public BaseA<Parent>{
friend class BaseA<Parent>;
public:
void test(int i){
printf("xxx--------->%s(), line = %d, i = %d\n",__FUNCTION__,__LINE__,i);
}
static const char *getServiceName() { return "media.audio_policy"; }
int value = 100;
};
int main(){
//1.父类BaseA<Parent>模板类指向子类对象Derived
BaseA<Parent> *b = new Derived();
b->test(999);
}