C++基礎之結構體做函數參數

說明:
將結構體作爲參數向函數中傳遞有值傳遞和地址傳遞兩種方式。

#include <iostream>
using namespace std;
#include<string>

struct Student
{
	string name;
	int age;
	int score;
};

/*
	1.值傳遞
*/
void printStudent1(struct Student s1)
{
	cout << s1.name << s1.age << s1.score << endl;

	s1.age = 24;//值傳遞不可以改變函數外面的值
}

/*
	2.地址傳遞
*/
void printStudent2(struct Student *p)
{
	cout << p->name << p->age << p->score << endl;

	p->age = 25;//地址傳遞可以改變函數外面的值
}

int main() 
{
	
	struct Student s1 = { "小李子",19,98 };
	
	printStudent1(s1);

	printStudent2(&s1);

	cout << s1.name << s1.age << s1.score << endl;

	system("pause");
	return 0;
}

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