Home  >  Article  >  Backend Development  >  What is the difference between C++ static functions and friend functions?

What is the difference between C++ static functions and friend functions?

WBOY
WBOYOriginal
2024-04-17 08:42:01561browse

Static functions are class methods that only access static members and do not receive this pointers; friend functions do not belong to the class and can access all members and receive this pointers.

C++ 静态函数与友元函数有什么区别?

The difference between static functions and friend functions in C

Static functions

  • Belongs to a class but does not belong to any specific object. It can also be called a class method.
  • Declared using the static keyword.
  • Only static members of the class can be accessed.
  • will not receive the this pointer.

Friend function

  • Does not belong to any class.
  • Use the friend keyword statement.
  • Can access all members of the class, including private members.
  • can receive this pointer.

Table summary

##Class membershipisNotAccess rightsClass static membersAll members of the classthis pointerNot acceptedCan be receivedDeclaration method
Features Static function Friend functions
static Keyword friend Keywords

Practical case

Static function example: Calculate circle Area

class Circle {
public:
    static double calculateArea(double radius) {
        return 3.14 * radius * radius;
    }
};

int main() {
    double radius = 5.0;
    double area = Circle::calculateArea(radius);
    cout << "圆的面积:" << area << endl;
    return 0;
}

Friend function example:Print the value of private member

class Student {
private:
    int age;

public:
    friend void printAge(Student& student);
};

void printAge(Student& student) {
    cout << "年龄:" << student.age << endl;
}

int main() {
    Student student;
    student.age = 20;
    printAge(student);
    return 0;
}

The above is the detailed content of What is the difference between C++ static functions and friend functions?. 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