CPP06-類的模版
//
// Created by 87572 on 20/7/10.
//
#include "../include/StateEight.h"
#include <iostream>
/**
* K1:-------------------------類的模版--------------------------------
* 1.就是java中的泛型編程
*
*/
class EightPerson {
};
class EightPersonSon:public EightPerson{
};
template<class T>
void swap(T t) {
}
template<class T>
class TemplateBase1 {
};
template <class T>
class TemplateSon1 :public TemplateBase1<T>{
};
template <class T,class T2>
class TemplateSon2 :public TemplateBase1<T2>{
};
class TemplateSon3 :public TemplateBase1<EightPerson>{
};
void useTemplate() {
swap<EightPerson>(EightPerson());
TemplateSon2<EightPerson,EightPerson> templateSon3();
}
/**
* K2:-----------------hpp文件------------------------
* 類模板的聲明和實現(xiàn)放到一個文件中,我們把這個文件命名為.hpp(這個是個約定的規(guī)則,并不是標(biāo)準(zhǔn),必須這么寫).
*/
/**
* K3:-------------類型轉(zhuǎn)換------------------
*
* 1.靜態(tài)類性轉(zhuǎn)換 static_cast
* 1) 進行上行轉(zhuǎn)換(把派生類的指針或引用轉(zhuǎn)換成基類表示)是安全的;
* 2) 進行下行轉(zhuǎn)換(把基類指針或引用轉(zhuǎn)換成派生類表示)時,由于沒有動態(tài)類型檢查,所以是不安全的。
* 3) 用于基本數(shù)據(jù)類型之間的轉(zhuǎn)換,如把int轉(zhuǎn)換成char,把char轉(zhuǎn)換成int。這種轉(zhuǎn)換的安全性也要開發(fā)人員來保證。
*2.動態(tài)類型轉(zhuǎn)換
* 1)進行上行轉(zhuǎn)換(把派生類的指針或引用轉(zhuǎn)換成基類表示)是安全的;
* 2)父類指針轉(zhuǎn)換成子類指針 不可以;子類->父類可以
* 3)基本類型,不可以.
*3.const 轉(zhuǎn)換
* 常量指針被轉(zhuǎn)化成非常量指針,并且仍然指向原來的對象;
* 常量引用被轉(zhuǎn)換成非常量引用,并且仍然指向原來的對象;
*
*
*
*/
void useChange(){
int a=10;
char b='C';
b= static_cast<char>(a);
auto *templateSon3=new TemplateSon2<EightPerson,EightPerson>();
auto *templateBase1=new TemplateBase1<EightPerson>();
templateSon3= static_cast<TemplateSon2<EightPerson, EightPerson> *>(templateBase1);
const int* p = NULL;
int* np = const_cast<int*>(p);
int* pp = NULL;
const int* npp = const_cast<const int*>(pp);
const int a2= 10; //不能對非指針或非引用進行轉(zhuǎn)換
// int b2 = const_cast<int>(a2); 不可以.
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。