cpp的宏和模板的简单介绍
宏处理器
编译阶段对代码进行预处理,简单的替换,不会进行安全检查
宏的名字大写,使用const代替宏,使用内联函数代替宏函数
关于#define 和ifdefine
关于\和#和##
宏延续运算符(\)
字符串常量化运算符(#)
标记粘贴运算符(##)
模板
模板函数语法
template <<#template parameters#>>
<#return type#> <#function name#>(<#function parameters#>) {
<#statements#>
}
模板类语法
template <<#template parameters#>>
class <#class name#> {
<#instance variables#>
public:
<#member functions#>
};
模板的默认参数
template <typename T=int>
强大的stl库就是使用模板写的哦
//
// main.cpp
// use_define_template
//
// Created by bikang on 16/10/25.
// Copyright (c) 2016年 bikang. All rights reserved.
//
#include <iostream>
#define PI 3.1416
#define SQUARE(x) x * x
#define SQUARE2(x) \
(x) * (x)
#define MAX(x,y) ( (x) > (y)?(x):(y))
//#和##
#define showData(n) (cout <<"#n="<<#n <<" p##n="<< p##n <<endl)
inline int maxInt(int x,int y) { if(x>y) return x;else return y;}
using namespace std;
void tdeftmp();
template <typename T>
T tmpSub(T x, T y) {
return x-y;
}
template <typename T=int>
class MyTempClass {
public:
void setVal(T &newVal){
val = newVal;
};
T& getVal(){return val;};
private:
T val;
};
int main(int argc, const char * argv[]) {
// insert code here...
tdeftmp();
return 0;
}
void tdeftmp(){
cout << "test tmp"<<endl;
//宏
cout << "PI=" << PI << endl;
cout << "SQUARE(3+2) "<<SQUARE(3+2) <<endl;
cout << "SQUARE2(3+2) "<<SQUARE2(3+2) <<endl;
cout << "maxInt(2, 3) " << maxInt(2, 3)<<endl;
cout << "MAX(2, 3) " << MAX(2, 3)<<endl;
//# ##
int p12 = 456;
showData(12);
//模板函数
cout << tmpSub(2,3)<<endl;
cout << tmpSub(2.1,3.3)<<endl;
//模板类
MyTempClass <int>mt;
int a = 5;
mt.setVal(a);
cout << mt.getVal() << endl;
MyTempClass<string> mt2;
string str1 = "hello cpp";
mt2.setVal(str1);
cout << mt.getVal()<<endl;
}