dululu / GitNote

0 stars 0 forks source link

快速学习C和C++,基础语法和优化策略(三) #18

Open dululu opened 5 months ago

dululu commented 5 months ago

函数 functions

内联函数 inline

程序运行效率,用空间换时间。

// 使用函数调用
int main()
{
    int num1 =20;
    int num2 = 30;
    int maxv = max_function(num1,num2);
    maxv = max_function(numn,maxv);
}
//
float max_function(float a,float b)
{
    if(a>b)
        return a;
    else
        return b;
}
//频繁调用max_function

可以用inline,用空间换时间。

int main()
{
    int num1 =20;
    int num2 = 30;
    int maxv = {   //示意图,没有函数调用,生成的机器代码变多。
    if(num1>num2)
        return num1;
    else
        return num2;}
    maxv = {
    if(numn>maxv)
        return numn;
    else
        return maxv;}
}
// 只会建议编译器执行这样的命令,编译器根据整体情况来判断
inline float max_function(float a,float b)
{
    if(a>b)
        return a;
    else
        return b;
}

使用操作

#define MAX_MACRO(a>b) ?(a):(b)  //比较大小
// 不局限于某一种特定的数据类型
// 宏 是文本替换
int num1 = 20,num2 = 30;
maxv = MAX_MACRO(num1++,num2++);
maxv = MAX_MACRO(num1++ > num2++) ?(num1++):(num2++) 
cout<< maxv << endl;  //31
cout <<"num2="<<num2<<endl; //mun2=32
//num1 =21,因为num1没有被再次调用

默认参数 Default arguments

函数重载 overloading

使用同样的函数名,但是做的是不同的事。

<cmath>
double round(double x);
float round(flaot x);
long duble round(long double x);

cpp 依赖参数列表来查询,选择不同的函数。

函数模板 templates

当函数的实现逻辑都非常相同的时候,就可以使用函数模板。

template<typename T>
T sum(T x, T y)
{
cout<<"The input type is" << typeid(T).name <<endl;
return x+y;
}
// 实例化
template double sum(double,double);
template char sum<>(char,char);
template int sum(int,int);

函数指针和函数引用 Function pointers and References