結構體做函數參數

結構體做函數參數

作用:將結構體作爲參數向指針中傳遞

傳遞方式有2種:

(1)值傳遞:在值傳遞中,修改形參,實參不會改變

/*打印輸出函數*/
//1.值傳遞
void printStudent(struct student stu)
{
    stu.age = 40; //在值傳遞中,修改形參,實參不會改變
    cout << "值傳遞子函數中:" << endl;
    cout << "姓名: " << stu.name << "  年齡: " << stu.age << "  分數:" << stu.score <<endl;
}

 

(2)地址傳遞:在地址傳遞中,修改形參,實參也會改變

//2.地址傳遞
void printStudent2(struct student * p)
{
    p->age = 30;  //在地址傳遞中,修改形參,實參也會改變
    cout << "地址傳遞子函數中:" << endl;
    cout << "姓名: " << p->name << "  年齡: " << p->age << "  分數:" << p->score << endl;
}

原代碼:

#include<iostream>
using namespace std;
#include<string>
void printStudent(struct student stu);

/*1.定義一個結構體*/
struct student
{
    string name;
    int age;
    int score;
}s1;

/*打印輸出函數*/
//1.值傳遞
void printStudent(struct student stu)
{
    stu.age = 40; //在值傳遞中,修改形參,實參不會改變
    cout << "值傳遞子函數中:" << endl;
    cout << "姓名: " << stu.name << "  年齡: " << stu.age << "  分數:" << stu.score <<endl;
}

//2.地址傳遞
void printStudent2(struct student * p)
{
    p->age = 30;  //在地址傳遞中,修改形參,實參也會改變
    cout << "地址傳遞子函數中:" << endl;
    cout << "姓名: " << p->name << "  年齡: " << p->age << "  分數:" << p->score << endl;
}

int main()
{
    struct student stu;
    stu.name = "小葉";
    stu.age = 22;
    stu.score = 99;

   
   // printStudent(stu);   //值傳遞
    printStudent2(&stu); //地址傳遞

    cout << "在main函數中打印輸出:" << endl;
    cout << "姓名: " << stu.name << "  年齡: " << stu.age << "  分數:" << stu.score << endl;

    return 0;
}


 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章