code.club

 找回密碼
 立即註冊
搜索
查看: 6328|回復: 2
打印 上一主題 下一主題

有關C++函數指標參數的用法

[複製鏈接]
跳轉到指定樓層
樓主
發表於 2019-3-9 13:33:57 | 只看該作者 回帖獎勵 |倒序瀏覽 |閱讀模式
#include <iostream>
#include <string>
using namespace std;

void swap1(int *, int *);
void swap2(int &,int &);

int main(){
        int x = 1, y = 2;
        int *p = &x;
        int *q = &y;
       
        swap1(p,q); //若原型是*p,*q則寫p,q即可。
        cout<<" x is "<<x<<" and y is "<<y<<endl;
        swap2(x,y); //若原型是&x,&y則寫x,y即可。
        cout<<" x is "<<x<<" and y is "<<y<<endl;
       
        swap1(&x,q);//若原型是*p,*q也可以寫&x,&y。
        cout<<" x is "<<x<<" and y is "<<y<<endl;
        swap2(*p,y);//若原型是&x,&y則也可以寫*p,*q。
        cout<<" x is "<<x<<" and y is "<<y<<endl;
       
       
        return 0;
}


void swap1(int *p, int *q){
        int temp = 0;
        temp = *p;
        *p = *q;
        *q = temp;
}

void swap2(int &i, int&j){
        int temp = 0;
        temp = i;
        i = j;
        j = temp;
}
回復

使用道具 舉報

沙發
 樓主| 發表於 2019-3-10 10:48:17 | 只看該作者
#include <iostream>
#include <string>
using namespace std;

void change1(int&); // 給值時不用另外加指標符號
void change2(int*); // 給值時要加上&的指標符號
int main(){
       
        int x = 100;
        int y = 100;
        change1(x);
        cout<<"x is now "<<x<<endl;
        change2(&y);
        cout<<"y is now "<<y<<endl;


return 0;       
}

void change1(int &i){
                i = 321; //這裡也不用再加上&
        }
void change2(int *i){
        *i = 123; //這裡要加上*的指標符號
}
回復 支持 反對

使用道具 舉報

板凳
 樓主| 發表於 2019-3-30 14:31:47 | 只看該作者
#include <iostream>
#include <cstdlib>
using namespace std;

int t1(int);
int t2(int*);//參數是指標型態,所以要輸入的是變數的位址
int t3(int&);//參數是參照型態,直接用變數下去它會自動取位址

int main(){
        int a,b,c;
        a = 10;
        b = 10;
        c = 10;
       
        cout<<t1(a)<<endl;
        cout<<t2(&b)<<endl;//參數預設是指標,表示要輸入該變數的位址,故加上&
        cout<<t3(c)<<endl;//參數預設是參照,表示輸入的變數是只取其位址,故不用再另加&
        cout<<a<<endl;//10
        cout<<b<<endl;//11
        cout<<c<<endl;//11
       

        return 0;
}

int t1(int i){
        i++;
        return i;
}

int t2(int *i){
        *i = *i + 1;//表示本來就是輸入變數的位址,所以要變成數值才能運算,故用*
        return *i;
}

int t3(int &i){
        i++;//本來就會直接取其位址,所以直接用值運算,不用另加 * 或 &
        return i;
}
回復 支持 反對

使用道具 舉報

您需要登錄後才可以回帖 登錄 | 立即註冊

本版積分規則

小黑屋|手機版|Archiver|code.club  

GMT+8, 2024-4-25 08:25 , Processed in 0.078422 second(s), 16 queries .

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回復 返回頂部 返回列表