C++ 快速入门指南

2019-08-11  本文已影响0人  samtake
C艹.jpg

内联函数

C++提供了程序内联机制来减少函数调用的开销。在函数定义的返回值类型前面加一个inline关键字,“建议”编译器函数代码复制到程序中,避免函数调用。

using std::cout;
using std::cin;
using std::endl;


inline double cube(const double side){
   return side*side*side;
}

void testInlineFunction(){
   double sideValue;
   for (int i=1 ; i<=3 ; i++) {
       cout << "enter the side length of your cube:";
       cin >>sideValue;
       
       cout << "side=" << sideValue << "cube=" << cube(sideValue) <<endl;
   }
}

引用以及引用形参

引用以和引用形参

int squareByValue(int number){
    return number *=number;
}

void squareByReference(int &numberRef){
    numberRef *=numberRef;
}

函数体内引用作为别名

int z = 3;
   int &z_alias = z;//int &z_alias;
   cout << "z= " << z << endl << " z_alias = "  <<  z_alias << endl;
   z = 7;
   cout << "z= " << z << endl << " z_alias = "  <<  z_alias << endl;

输出

z= 3
 z_alias = 3
z= 7
 z_alias = 7

并且为初始化的引用int &z_alias;会导致错误

Declaration of reference variable 'z_alias' requires an initializer

空形参列表

在C++中,可以用void指定也可以通过在括号内不写任何语句定义空形参列表。如下两个函数是等价的:

void print();
void print(void);

默认实参

int boxVolume(int length = 1, int width = 1, int height = 1);

void testDefaultArgument(){
    cout << "default = " <<boxVolume() << endl;
    
    cout << "length  = 2 : " <<boxVolume(2) << endl;
    
    cout << "length  = 2 , width =3 : " <<boxVolume(2,3) << endl;
    
    cout << "length  = 2 , width =3 , height = 4 : " <<boxVolume(2, 3, 4) << endl;
}


int boxVolume(int length, int width, int height){
    return length*width*height;
}

一元作用域运算符

C++提供了一元作用域运算符,可以在含有与全局变量名的局部变量的域中访问该全局变量。

int number = 7;
void testUnaryOperation(){
    double number = 10.7;
    
    cout << "location number = " << number <<endl;
    
    cout << "gloable number = " << ::number <<endl;
    
}

输出

location number = 10.7
gloable number = 7

函数重载

void functionOverloading(){
   cout << square(7) <<endl;
   cout << square(0.5) <<endl;
}

int square(int x){
   cout << "integer : ";
   return x*x;
}

double square(double x){
   cout << "double : ";
   return x*x;
}

输出

integer : 49
double : 0.25

函数模版

重载函数用于对不同数据类型的程序逻辑执行相似操作。如果各种数据类型的程序逻辑和操作是完全相同的,那么使用函数模版可以更加简洁、方便的执行重载。

template <class T>
T maximum(T value1, T value2, T value3 ) {
    T maximumValue = value1;
    
    if (value2 > maximumValue) {
        maximumValue = value2 ;
    }
    
    if (value3 > maximumValue) {
        maximumValue = value3 ;
    }
    
    return maximumValue;
}

关于C++部分的下一篇应该是C++ 类与对象,有空再补吧~~~

demo链接🔗https://github.com/samtake/C-review

上一篇 下一篇

猜你喜欢

热点阅读