Home  >  Article  >  Backend Development  >  Detailed explanation of C++ member functions: definition and calling mechanism of object methods

Detailed explanation of C++ member functions: definition and calling mechanism of object methods

WBOY
WBOYOriginal
2024-04-29 21:21:01500browse

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++ 成员函数详解:对象方法的定义与调用机制

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn