C++結構體中const使用場景

看如下代碼: 

#include<iostream>
using namespace std;

#include<string>


//結構體
struct Student {

	string name;
	int age;
	int score;

}st3;

//值傳遞
void printStufdents(struct Student st2) {
	cout << "子函數" << endl;
	st2.age = 150;
	cout << "名字:" << st2.name << "	年齡:" << st2.age << "	分數:" << st2.score << endl;
}

//指針傳遞只佔四個字節  節省內存空間  而且不會複製新的副本出來
void printStufdents(struct Student *s) {
	cout << "子函數" << endl;
	s->age = 150;
	cout << "名字:" << s->name << "	年齡:" << s->age << "	分數:" << s->score << endl;
}



int main() {

	
	struct Student st2 = { "張三丰",120,70 };
	cout << "名字" << st2.name << "年齡" << st2.age << "分數" << st2.score<< endl;

	printStufdents(st2);


	system("pause");
}

1,地址傳遞只佔四個字節  節省內存空間  而且不會複製新的副本出來

2,地址傳遞有個問題,會改變地址的值,爲了防止誤操作,我們引入了const關鍵字修飾指針

#include<iostream>
using namespace std;

#include<string>


//結構體
struct Student {
	string name;
	int age;
	int score;
}st3;

void printStufdents(struct Student st2) {
	cout << "子函數" << endl;
	st2.age = 150;
	cout << "名字:" << st2.name << "	年齡:" << st2.age << "	分數:" << st2.score << endl;
}

//指針傳遞只佔四個字節  節省內存空間  而且不會複製新的副本出來
void printStufdents(const struct Student *s) {
	cout << "子函數" << endl;
	s->age = 150;
	cout << "名字:" << s->name << "	年齡:" << s->age << "	分數:" << s->score << endl;
}

int main() {

	struct Student st2 = { "張三丰",120,70 };
	cout << "名字" << st2.name << "年齡" << st2.age << "分數" << st2.score<< endl;

	printStufdents(st2);
	system("pause");
}

 

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