预处理器在编译之前,根据程序员的指示决定要编译的内容。
宏
宏定义一般有两种,定义函数和常量
当文中用到较多相同的常量时:应该用宏定义
在宏定义函数时:应该多用括号。
使用宏避免多次包含
1 c++的头文件一般用来声明函数和类,若有一个class2类要用到class1中的类的话,应该用宏,避免多次包含,提高效率
2 注意使用宏一般不考虑数据数据类型
3 尽量的不要自己编写宏函数,尽可能的使用const,而不是宏常量
#ifndef HEADER1_H
#define HEADER1_H
#include "class1.h"
class class2
{
}
#endif
模板
1 模板函数
如果有一个函数,他使用不同类型的变量及输出,则可以运用模板编写
运用模板函数,返回两个变量中最大的一个
#include "stdafx.h"
#include "iostream"
#include "string"
using namespace std;
template<typename T>
const T&getmax(T&num1, T&num2)
{
if (num1 > num2)
return num1;
else
{
return num2;
}
}
int main()
{
int a = 2; int b = 3;
cout<<getmax(a,b)<<endl;
return 0;
}
2 模板类
含有两个成员属性的模板类
#include "stdafx.h"
#include "iostream"
#include "string"
using namespace std;
template<typename T1 = int, typename T2 = double>
class compares
{
private:
T1 number1;
T2 number2;
public:
compares(const T1&num1, const T2&num2)
{
number1 = num1;
number2 = num2;
if (number1 >= number2)
cout << "the max is " << number1 << endl;
else
{
cout << "the max is " << number2<<endl;
}
}
};
int main()
{
compares<>maxnumber(3, 3.14);
compares<char, char>maxaltter('a', ' b');
return 0;
}
3 模板类和静态成员
在运用静态成员时,应在定义属性前加上static,
静态成员需要初始化:一般为
template<typename parameters> statictype classname<template arguments>::staticvarname