(7)C++ 函数2

一、内联函数

通常程序在调用函数时,程序会跳转到另一个地址上,意味着会多花开销。使用内联函数,编译器能够将函数调用替换成函数代码。这样会变得稍快一些

在函数原型的地方使用加了inline的函数定义

#include<iostream>
using namespace std;
inline int sum(int a, int b) { return a + b; }
void main() {
    sum(3, 4);
}

优点时速度更快些,代价是占用更多的内存。

二、引用变量

1.相当于起了个别名,使用 & 

必须在引用时进行初始化

    int r = 3;
    int& b = r;

2.引用作为参数

3.引用的属性

 

4.引用用于结构

 

5.引用用于类对象

 

三、默认参数

 默认参数值必须在函数最右边,默认值在原型上指定

#include<iostream>
using namespace std;
int sum(int a, int b = 10);
void main() {
    cout << sum(2);
}

int sum(int a, int b) {
    return a + b;
}

 

四、函数重载

#include<iostream>
using namespace std;
int sum(int a, int b);
int sum(int a, int b, int c);
void main() {
    cout << sum(2,3,4);
}

int sum(int a, int b) {
    return a + b;
}
int sum(int a, int b,int c) {
    return a + b + c;
}

 

 

五、函数模板

1.模板

#include<iostream>
using namespace std;
template<typename T>
void Swap(T &a,T &b) {
    T t;
    t = a;
    a = b;
    b = t;
}

void main() {
    int a = 8;
    int b = 100;
    Swap(a, b);
    cout << a << "  " << b << endl;

    double c = 8.5;
    double d = 100.5;
    Swap(c, d);
    cout << c << "  " << d << endl;
}

 2.重载模板

允许使用函数重载功能

#include<iostream>
using namespace std;
template<typename T>
void Swap(T &a,T &b) {
    T t;
    t = a;
    a = b;
    b = t;
}
template<typename T>
void Swap(T& a, T& b,int w) {
    T t;
    t = a*w;
    a = b*w;
    b = t;
}

void main() {
    int a = 8;
    int b = 100;
    Swap(a, b);
    cout << a << "  " << b << endl;

    double c = 8.5555;
    double d = 100.5555;
    Swap(c, d,10);
    cout << c << "  " << d << endl;
}

3.显示具体化

一套模板不一定会对所有的变量同用,比如想要交换结构体的某部分这时候就需要指定具体的变量

指定变量名,会优先使用指定的函数

#include<iostream>
using namespace std;
struct student {
    int age;
    string name;
};

template<typename T>
void Swap(T& a, T& b) {
    T t;
    t = a;
    a = b;
    b = t;
}

template<typename T>
void Swap(student a, student b) {
    student temp;
    temp.age = a.age;
    a.age = b.age;
    b.age = temp.age;
}

void main() {
    student stu1 = { 20,"TOM" };
    student stu2 = { 100,"老子" };
    cout << "交换前stu1 " << stu1.age << endl;
    cout << "交换后stu2 " << stu2.age << endl;

    Swap(stu1, stu2);
    cout << "交换前stu1 " << stu1.age << endl;
    cout << "交换后stu2 " << stu2.age << endl;
}

 

转载于:https://www.cnblogs.com/buchizaodian/p/11526910.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值