Home > Backend Development > C++ > Can C++ static functions access non-static member functions?

Can C++ static functions access non-static member functions?

WBOY
Release: 2024-04-17 10:24:02
Original
991 people have browsed it

In C, static functions cannot directly access non-static member functions. Solutions include: 1. Access through object pointers; 2. Access through class scope operators.

C++ 静态函数可以访问非静态成员函数吗?

Static function in C accesses non-static member function

In C, static function is a special member function. It is not associated with any specific object in the class. This means that static functions cannot directly access non-static member functions (i.e. ordinary member functions).

However, this limitation can be solved in the following two ways:

1. Access through object pointer:

Create an object pointing to the current class pointer, and then use the pointer to access the non-static member function. For example:

class MyClass {
public:
    static void staticFunction() {
        MyClass* obj = new MyClass();
        obj->nonStaticFunction();
        delete obj;
    }

    void nonStaticFunction() {
        // ...
    }
};
Copy after login

2. Access through class scope:

If the non-static member function is public, you can access it through class scope operator (::) for access. For example:

class MyClass {
public:
    static void staticFunction() {
        MyClass::nonStaticFunction();
    }

    static void nonStaticFunction() {
        // ...
    }
};
Copy after login

Practical case:

Suppose we have a Student class, which contains a member function getGrade() and a static function printGrade(). printGrade() Requires access to getGrade() to print student grades.

class Student {
public:
    int grade;

    void getGrade() {
        // 获取学生的成绩
    }

    static void printGrade(Student* student) {
        student->getGrade();
        // 通过对象指针访问非静态成员函数
    }

    static void printGrade() {
        Student student;
        student.getGrade();
        // 通过类作用域访问非静态成员函数
    }
};
Copy after login

In this case, printGrade() can be accessed both through the object pointer and getGrade() through the class scope.

The above is the detailed content of Can C++ static functions access non-static member functions?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template