C++結構體作爲函數參數傳參

#include<iostream>
using namespace std;

#include<string>


//結構體
struct Student {

	string name;
	int age;
	int score;

}st3;


/*
 *結構體作爲函數參數傳參
 */
//值傳遞
void printStufdent1(struct Student st3) {
	cout << "子函數" << endl;
	st3.age = 100;

	cout << "名字:" << st3.name << "	年齡:" << st3.age << "	分數:" << st3.score << endl;

}
//地址傳遞
void printStufdent2(struct Student * p) {
	p->age = 200;
	cout << "子函數" << endl;
	cout << "名字:" << p->name << "	年齡:" << p->age << "	分數:" << p->score << endl;

}


int main() {

	struct Student st1;
	st1.name = "zhangsan";
	st1.age = 18;
	st1.score = 60;
	//cout << "名字" << st1.name << "年齡" << st1.age << "分數" << st1.score<< endl;
	struct Student st2={"李四",20,70};
//	cout << "名字" << st2.name << "年齡" << st2.age << "分數" << st2.score<< endl;
	
	
	st3.name = "王五";
	st3.age = 19;
	st3.score = 59;

	printStufdent1(st3);
	cout << "main函數" << endl;
	cout << "名字:" << st3.name << "	年齡:" << st3.age << "	分數:" << st3.score << endl;

	printStufdent2(&st3);
	cout << "main函數" << endl;
	cout << "名字:" << st3.name << "	年齡:" << st3.age << "	分數:" << st3.score << endl;

	system("pause");
 }

從結果我們知道結構體作爲函數的參數傳參有兩種形式 

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