ah? Can a function be defined in a structure in C++? !

Saturday afternoon, June 3, 2023:

When I was watching the dictionary tree tutorial today, I found that there are functions defined in the structure of the sample code!

But I have a question, that is, what is the use and significance of defining a function in a structure, and why there is such a syntax.


 for example:

#include<iostream>
using namespace std;

struct Student{
	string id,name;
	void displayStudent(){
		cout<<"id="<<id<<" , "<<"name="<<name<<endl;
	}
};

int main(){
	Student stu1;
	stu1.id="2023001001";
	stu1.name="小明";
	stu1.displayStudent();
	return 0;
}

It is also possible to define a function inside a structure and then implement the function outside the structure:

#include<iostream>
using namespace std;

struct Student{
	string id,name;
	void displayStudent();
};

void Student::displayStudent(){
	cout<<"id="<<id<<" , "<<"name="<<name<<endl;
}

int main(){
	Student stu1;
	stu1.id="2023001001";
	stu1.name="小明";
	stu1.displayStudent();
	return 0;
}

 

 

Guess you like

Origin blog.csdn.net/m0_61629312/article/details/131020663