char ch;
ifs >> ch;
ifs.eof();//判断这个文件是否为空。
/**
* c++范型编程,利用模版技术:函数模版和类模版
*/
//T 通用类型,虚拟类型。
//自动类型推导,一致的数据类型才可以使用。
//函数声明和定义。typename 可以用class 替换。
template<class T>
void zaneSwap(T &a,T &b){
T temp = a;
a = b;
b = temp;
}
/**
* 1.普通函数和模版函数重载,优先调用不同函数。
* 2.如果强制调用重载模版类,用空模版空参数列表<>来调用。
*/
void myPrint(int a,int b){
cout << "普通打印 函数调用。"<<endl;
}
template<typename T>
void myPrint(T a,T b){
cout << "模版打印 函数调用。"<<endl;
}
/**
* 模版的局限性
* 针对自定义的类型进行判等。 等操作。
* 可以通过重载==号进行解决。
*
*/
template <typename T>
bool myCompare(T a,T b){
if(a == b){
return true;
}
return false;
}
class Person{
};
//可以通过下面这种具体化的判等。 具体化的操作。
template<> bool myCompare(Person p1,Person p2){
//具体实现。。。。。。
return true;
}
int main() {
int a = 10;
int b = 20;
int *c = new int(30);
int *d = new int(40);
myPrint(a,b);//这里调用的是普通打印函数。
myPrint<>(a,b);//如果强制调用重载模版类,用空模版空参数列表<>来调用。
zaneSwap(c,d);//自动类型推导
// zaneSwap<int>(10,20);//显示指定类型
cout << "c:"<<*c<<endl;
cout << "d:"<<*d<<endl;
return 0;
}
/**
* 类模版 与 函数模版的区别。
* 类模版没有自动推导功能,只能显示调用。
*/
template<typename NameType,typename AgeType = int>//这是类模版独有的,确定类型。
class Person{
public:
Person(NameType name,AgeType age){
this->m_name = name;
this->m_age = age;
}
NameType m_name;
AgeType m_age;
};
int main(){
Person<string,int> p1("孙悟空",99);
Person<string> p2("猪八戒",999); //这里直接在类模版的时候确定了类型,就无需在这里确定第二个参数类型。
cout << p1.m_name<<endl;
cout << p1.m_age<< endl;
cout << p2.m_name<<endl;
cout << p2.m_age<< endl;
return 0;
}
/**
* 类的成员函数,类创建的时候,就创建出来了。
* 模版函数是函数调用的时候才创建出来。
*/
class Person1{
public:
Person1(){}
void showPerson1(){
cout << "Person1 show"<<endl;
}
};
class Person2{
public:
Person2(){}
void showPerson2(){
cout << "Person2 show"<<endl;
}
};
template <typename T>
class MyPerson{
public :
MyPerson() {
}
T obj;
void showPerson1(){
obj.showPerson1();
}
void showPerson2(){
obj.showPerson2();
}
void showInfo(){
cout<<"模版类showInfo"<<endl;
}
};
//模版类作为参数如何传递。这里模版类是什么就传入什么,MyPerson<Person1>代表。
void test01(MyPerson<Person1> &p){
p.showInfo();
};
//通过参数模版化进行传递。
template<typename T>
void test02(MyPerson<T> &p){
p.showInfo();
cout << typeid(T).name()<<endl;//打印T类型。
}
//整个类进行模版化。
template<typename T>
void test03(T &var){
var.showInfo();
cout << typeid(T).name()<<endl;//打印T类型。
}
int main(){
MyPerson<Person1>person1;
person1.showPerson1();
test01(person1);
test02(person1);
test03(person1);
MyPerson<Person2> person2;
person2.showPerson2();
return 0;
}
c++教程2021-6-22学习笔记
最新推荐文章于 2022-12-03 12:07:21 发布