1 c++内联函数
概念: 内联函数是c++为提高程序运行速度的一项改进。内联函数编译器将使用相应的函数代码替换函数调用。
对于内联代码,程序无需跳到另一个位置处执行代码,再跳回来。因此,!内联函数的运行速度比常规函数稍快,但代价是需要占用更多的内存。
使用内联函数:
-
在函数声明前加上关键字inline。
-
在函数定义前加上关键字inline。
延伸阅读
Inline Versus Macros
The inline facility is an addition to C++. C uses the preprocessor #define statement to provide macros, which are crude implementations of inline code. For example, here’s a macro for squaring a number:#define SQUARE(X) X*X
This works not by passing arguments but through text substitution, with the X acting as a symbolic label for the “argument”:
a = SQUARE(5.0); is replaced by a = 5.0*5.0; b = SQUARE(4.5 + 7.5); is replaced by b = 4.5 + 7.5 * 4.5 + 7.5; d = SQUARE(c++); is replaced by d = c++*c++;
Only the first example here works properly. You can improve matters with a liberal application of parentheses:
#define SQUARE(X) ((X)*(X))
Still, the problem remains that macros don’t pass by value. Even with this new definition, >SQUARE(c++) increments c twice, but the inline square() function in Listing 8.1 evaluatesc, 。>passes that value to be squared, and then increments c once. The intent here is not to show you >how to write C macros. Rather, it is to suggest that if you have been using C macros to perform function-like services, you should consider converting them to C++ inline functions.
NoteListing 8.1 inline.cpp ------------------------------------------------------------ // inline.cpp -- using an inline function #include <iostream> // an inline function definition inline double square(double x) { return x * x; } int main() { using namespace std; double a, b; double c = 13.0; a = square(5.0); b = square(4.5 + 7.5); // can pass expressions cout << "a = " << a << ", b = " << b << "\n"; cout << "c = " << c; cout << ", c squared = " << square(c++) << "\n"; cout << "Now c = " << c << "\n"; return 0; } -------------------------------------------------------------
注:摘自c++ Primer Plus(第六版)
2引用变量
引用变量: 引用是已定义的变量的别名(另一个名称)。一旦与某个变量关联起来,就将一直效忠于他。
用法: 引用常被用作函数参数,使得函数中变量名成为程序中的变量别名(也就是按引用传递)。
按值传递导致被调用函数使用调用程序的值拷贝,按引用传递允许被调用的函数能够访问调用函数中的变量。
3默认参数
默认参数: 默认参数指的是当函数调用中省略了实参时自动使用一个值。
如何设置默认值呢?
必须通过原型函数,由于编译器通过查看原型来了解函数所使用的参数数目,因此函数原型也必须将可能的默认参数告知程序。方法就是将值赋给原型中的参数。例如,left( )函数原型如下:
char * left(const char * str,int n=1);
(用户在使用的时候,如果只输入了第一个参数,则按照默认n=1;如果用户输入了第二个参数,则n的值被覆盖。)
4函数重载
函数重载(函数多态): 函数重载允许多个函数可以同名,但区别是使用不同的参数列表,通过函数重载来设计一系列函数—他们完成相同的工作,但使用不同参数列表。
(编译器就是根据函数的参数列表的不同,确定重载哪一个函数。虽然函数重载很吸引人,但也不要滥用。仅当函数基本执行相同的任务,但使用不同形式的数据时,才应函数重载)
5函数模版
函数模版: 函数模版就是通用的函数描述。也就是说使用泛型来定义函数,其中泛型可用具体的类型替换。通过将类型作为参数参数传递给模版,可使编译器生成该类型的函数。
例如一个交换模版:
template<typename AnyType> //关键字template和typename是必须的
void Swap(AnyType &a,AnyType &b) //许多程序员习惯使用T代替AnyType
{
AnyType temp;
temp=a;
a=b;
b=temp;
}
(在c++98添加关键字typename之前,c++使用关键字class来创建模版。这两种关键字是等价的。如果要多个将同一种算法用于不同类型的函数,请使用模版。)
6.参考资料
C++ Primer Plus(第六版)