天天看點

c++ primer學習筆記(5)-函數(1)

一.基礎

1.無參函數

#include <iostream>
#include <string>

//無參數,無傳回值
void SayHello()
{
    std::cout << "Hello" << std::endl;
}
//效果相同
void SayHello2(void)
{
    std::cout << "Hello" << std::endl;
}
      

2.有參函數

//有參數,無傳回值
void Subtract(int a,int b)
{
    std::cout << "result:";
    std::cout << a-b << std::endl;
}
      

3.有傳回值

//有傳回值
int Max(int a,int b)
{
    if(a>b)
        return a;
    return b;
}
      

測試代碼

SayHello();
Subtract(10,5);
std::cout << "Max result:";
std::cout << Max(11,22)<< std::endl;
      
c++ primer學習筆記(5)-函數(1)

二.傳參

1.非引用形參(值類型複制)

//無效
void Zero1(int p)
{
    p=0;
}
      

2.指針形參

//更改有效
void Zero2(int *p)
{
    *p=0;
}
      

注意:兩者都是需要複制

Test

int i = 42;
    int *p = &i;
    std::cout << "i: " << i << '\n';   // prints i: 42
    Zero1(i);
    std::cout << "i: " << i << '\n';   // prints i: 42
    Zero2(p);
    std::cout << "after i: " << i << '\n';   // prints i: 0
      
c++ primer學習筆記(5)-函數(1)

3.const形參(參數不可更改)

//編譯通過
int Fix(int a)
{
    if(a>10)
      a=10;
    return a;
}

int ReadFix(const int a)
{
    //錯誤,無法編譯
    if(a>10)
      a=10;
    return a;
}
      

4.引用形參(引用是别名)

經典的swap方法

//無效
void swap1(int v1, int v2)
{
    int tmp = v2;
    v2 = v1;    
    v1 = tmp;
}    

//有效
void swap2(int &v1, int &v2)
{
    int tmp = v2;
    v2 = v1;
    v1 = tmp;
}
      

Test1

int i = 10;
int j = 20;
cout << "Before swap():\ti: "
     << i << "\tj: " << j << endl;
swap1(i, j);
cout << "After swap():\ti: "
     << i << "\tj: " << j << endl;
      
c++ primer學習筆記(5)-函數(1)

Test2換做swap2的結果

c++ primer學習筆記(5)-函數(1)

5.const引用

bool isShorter(const string &s1, const string &s2)
{
    return s1.size() < s2.size();
}
      
int incr(int &val)
{
    return ++val;
}
      
int main()
{
         short v1 = 0;
         const int v2 = 42;
         int v3 = incr(v1);   // error: v1 is not an int
         v3 = incr(v2);       // error: v2 is const
         v3 = incr(0);        // error: literals are not lvalues
         v3 = incr(v1 + v2);  // error: addition doesn't yield an lvalue
         int v4 = incr(v3);   // ok: v3 is a non const object type int
         return 0;
}