結構體中添加const關鍵字來防止誤操作

1.未添加const關鍵字

void printArry(struct MyStruct * stu)
{
	stu->age = 23;
	cout << "打印函數輸出" << endl;
	cout << "姓名:" << stu->name << "  年齡:" << stu->age << "  id:" << stu->id << endl;
}

在未添加const關鍵字之前,修改形參,實參也會跟着改變。

2.添加const關鍵字防止誤操作

void printArry(const struct MyStruct * stu)
{
//	stu->age = 23;  //提示錯誤,表達式左值不可修改
	cout << "打印函數輸出" << endl;
	cout << "姓名:" << stu->name << "  年齡:" << stu->age << "  id:" << stu->id << endl;
}

將函數中形式參數改爲指針,不會複製新的副本出來且可以減少內存空間,添加const修飾結構體,可以防止誤操作。

 3.源代碼

#include<iostream>
using namespace std;
#include<string>
void printArry(const struct MyStruct* stu);

struct MyStruct
{
	string name;
	int age;
	int id;
};

void printArry(const struct MyStruct * stu)
{
//	stu->age = 23;  //提示錯誤,表達式左值不可修改
	cout << "打印函數輸出" << endl;
	cout << "姓名:" << stu->name << "  年齡:" << stu->age << "  id:" << stu->id << endl;
}

int main()
{
	struct MyStruct stu;
	stu.name = "小葉";
	stu.age = 22;
	stu.id = 9354;
	printArry(&stu);
  //cout << "main函數輸出:" << endl;
  //cout << "姓名:" << stu.name << "  年齡:" << stu.age << "  id:" << stu.id << endl;
	return 0;
}

 

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