In C, friend functions can be declared outside the class, but they must be immediately adjacent to the definition of the class, starting with the friend keyword, and are not restricted by the class scope.
#C Can friend functions be declared outside a class?
Preface
Friend functions are special functions that access private/protected members of a class outside the class. They are declared outside the class definition. This article will discuss the out-of-class declaration rules for friend functions in C and provide practical examples for illustration.
Outside-class declaration rules
In C, friend functions can be declared outside the class, but you need to pay attention to the following rules:
friend
keyword. Practical case
The following is a practical case showing the declaration of a friend function outside the class:
// 类 Person 定义 class Person { private: std::string name_; // 私有成员变量 public: Person(const std::string& name) : name_(name) {} }; // 友元函数声明(在 Person 类外) friend std::ostream& operator<<(std::ostream& os, const Person& person); // 主函数 int main() { Person p("John Doe"); std::cout << p << std::endl; // 调用友元函数 } // 友元函数定义(在 Person 类外) std::ostream& operator<<(std::ostream& os, const Person& person) { os << person.name_; return os; }
Code explanation
In this example:
Person
The class definition contains a private member variable name_
. operator<<
The function is declared as a friend function of the Person
class and placed after the definition of the class. Person
object is created and its name_
value is output, which requires calling the friend function. name_
private member variable and outputs its value. Conclusion
Friend functions in C can be declared outside a class, but must be immediately adjacent to the class definition and using the friend
keyword. The declaration of a friend function is not restricted by the class scope, thus providing the flexibility to access private members outside the class. For clarity and readability, it is recommended to declare friend functions near the definition of the class.
The above is the detailed content of Can C++ friend functions be declared outside a class?. For more information, please follow other related articles on the PHP Chinese website!