Member functions are functions defined in a class and are used to operate class data and perform tasks. Its definition syntax is: define member function: return_type class_name::function_name(parameters) call member function: object.function_name(parameters)
C Detailed explanation of member function: Definition and calling mechanism of object methods
Preface
In C, member functions are functions defined in a class and are used to manipulate data in the class and perform specific tasks. Understanding member functions is crucial to mastering C programming.
Definition of member functions
Member functions are defined using the following syntax:
return_type class_name::function_name(parameters) { // 函数体 }
For example:
class Person { public: string name; // 构造函数 Person(string n) : name(n) {} // 成员函数 void greet() { cout << "Hello, my name is " << name << endl; } };
In this example, greet()
is a member function of class Person
, which is used to output the name of the object.
Call member functions
Member functions are called through objects. The syntax is as follows:
object.function_name(parameters);
For example:
Person john("John Doe"); john.greet(); // 调用 greet() 成员函数
Practical case
Consider a simple student management system in which each student is represented by a Student
Class representation:
class Student { public: string name; int age; float gpa; // 构造函数 Student(string n, int a, float g) : name(n), age(a), gpa(g) {} // 成员函数:获取学生信息 string get_info() { return "Name: " + name + ", Age: " + to_string(age) + ", GPA: " + to_string(gpa); } };
In the main function, we can create the Student
object and call its get_info()
member function:
int main() { Student student1("Jane Doe", 20, 3.5); cout << student1.get_info() << endl; return 0; }
The output result is:
Name: Jane Doe, Age: 20, GPA: 3.5
The above is the detailed content of Detailed explanation of C++ member functions: definition and calling mechanism of object methods. For more information, please follow other related articles on the PHP Chinese website!