Detailed Explanation of Member Variables and Member Functions of C++ Classes

Class can be regarded as a data type, which is similar to ordinary data types, but different from ordinary data types. Class This data type is a collection that contains member variables and member functions.

Like ordinary variables, member variables of a class also have data types and names, and occupy fixed-length memory. However, you cannot assign values ​​to member variables when defining a class, because a class is just a data type or a template, which does not occupy memory space itself, and the value of a variable requires memory to store.

A member function of a class is the same as a normal function, and has a return value and a parameter list. The difference between it and a general function is that a member function is a member of a class, appears in the class body, and its scope of action is determined by the class; and Ordinary functions are independent, and their scope is global or located in a certain namespace.

In the previous section, we gave the definition of the Student class in the example, as follows:

class Student{
public:
    //成员变量
    char *name;
    int age;
    float score;
    //成员函数
    void say(){
        cout<<name<<"的年龄是"<<age<<",成绩是"<<score<<endl;
    }
};

This code defines member functions in the class body. You can also only declare the function in the class body, and put the function definition outside the class body, as shown in the following figure:

class Student{
public:
    //成员变量
    char *name;
    int age;
    float score;
    //成员函数
    void say();  //函数声明
};
//函数定义
void Student::say(){
    

Guess you like

Origin blog.csdn.net/m0_68539124/article/details/129471792