Friend functions allow cross-class access to private or protected members. The syntax is: class ClassName {protected: // Private or protected members}; friend declares a friend function;. To call a friend function, use the dot operator and a class instance: obj.value = 10; printValue(obj);. In the actual case, the friend function is used to compare the length of two strings and accesses the private member length().
A friend function is a special type of function in C that can access another Private and protected members of the class. This is useful when you need to access data across classes or implement special functionality.
The syntax of friend function is as follows:
class ClassName { protected: // 私有或受保护成员 }; friend 声明友元函数;
For example:
class MyClass { protected: int value; }; friend void printValue(MyClass&); // 声明友元函数
To call a friend function, you can use the dot operator (.
) and a class instance:
MyClass obj; obj.value = 10; // 访问私有成员 printValue(obj); // 调用友元函数
The following is a practical case using a friend function:
// 友元函数用于比较两个字符串的长度 bool compareStringLength(const string& s1, const string& s2) { return s1.length() > s2.length(); } // 测试友元函数 int main() { string str1 = "Hello"; string str2 = "World"; // 使用友元函数比较字符串长度 if (compareStringLength(str1, str2)) { cout << "str1 is longer than str2" << endl; } else { cout << "str2 is longer than str1" << endl; } return 0; }
In this example, the compareStringLength
function is a friend function that can access the private member length()
of the string
class.
The above is the detailed content of Detailed explanation of C++ friend functions: How to call friend functions?. For more information, please follow other related articles on the PHP Chinese website!