一、内联函数

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

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

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

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

二、引用变量

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

必须在引用时进行初始化

    int r = ;
int& b = r;

2.引用作为参数

3.引用的属性

4.引用用于结构

5.引用用于类对象

三、默认参数

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

#include<iostream>
using namespace std;
int sum(int a, int b = );
void main() {
cout << sum();
} 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(,,);
} 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 = ;
int b = ;
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 = ;
int b = ;
Swap(a, b);
cout << a << " " << b << endl; double c = 8.5555;
double d = 100.5555;
Swap(c, d,);
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 = { ,"TOM" };
student stu2 = { ,"老子" };
cout << "交换前stu1 " << stu1.age << endl;
cout << "交换后stu2 " << stu2.age << endl; Swap(stu1, stu2);
cout << "交换前stu1 " << stu1.age << endl;
cout << "交换后stu2 " << stu2.age << endl;
}

最新文章

  1. nodejs模块——http模块
  2. js内存泄漏
  3. 从0 开始 WPF MVVM 企业级框架实现与说明 ---- 第四讲 WPF中 ControlTemplate
  4. effective c++ 条款23 perfer nonmember nonfreind function to member function
  5. 重新想象 Windows 8.1 Store Apps (81) - 控件增强: 加载本地 html, 智能替换 html 中的 url 引用, 通过 Share Contract 分享 WebView 中的内容, 为 WebView 截图
  6. 67、django之模型层(model)--查询补充及mookie
  7. StringMVC @RequestMapping method属性
  8. 损失函数 hinge loss vs softmax loss
  9. 。net加密解密相关方法
  10. 24, CSS 构造超链接
  11. 项目案例【Net Core】如何注入多个服务实现类
  12. spring boot启动后执行方法
  13. Fenng早年间对推荐系统的思考
  14. IDEA多线程调试设置
  15. 本地项目文件夹同步到GitLab的操作步骤
  16. ThinkPHP3 和 ThinkPHP5 不是一个团队做的
  17. 继承类中static数据值
  18. git上传的文件夹为空的时候
  19. const T &amp; 的适用范围
  20. ThinkPHP关于模板的一些嵌套、IF判断使用

热门文章

  1. 119、TensorFlow如何创建计算图
  2. python 字符串str和json格式转换
  3. ubuntu+qt+opencv
  4. Linux对用户态的动态内存管理
  5. Spring Boot开启的2种方式
  6. Python做个小游戏
  7. mySQL部分疑问和小结(orale)
  8. sqlacodegen:通过mysql语句生成sqlalchemy的model
  9. 工作中SQL语句的优化
  10. Docker基础(下)