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.
The difference between static functions and friend functions in C
Static functions
Friend function
Table summary
Features | Static function | Friend functions |
---|---|---|
is | Not | |
Class static members | All members of the class | |
Not accepted | Can be received | |
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!