In C, friend functions and access control may conflict. To access private members, you can declare the member as protected or use a proxy function. For example, the Student class has private members name and score, and the friend functions printName and printScore can print these members respectively.
C Conflict between friend functions and access control
In C, friend functions can access private members of a class Non-member function. However, when it comes to access control, friend functions may encounter conflicts with class member access control.
Access Control
C provides three access control levels:
Friend functions
Friend functions are declared through the friend
keyword. Friend functions have access to all members of a class, regardless of access control level. However, friend functions do not become part of the class.
Access control violation
An access control violation occurs when a friend function attempts to access a private member. For example:
class MyClass { private: int x; friend void printX(MyClass& obj) { std::cout << obj.x << std::endl; } };
In this example, the printX
function is a friend of the class, but it is trying to access the private member x
. This can cause compiler errors.
Resolving conflicts
To resolve access control conflicts, you can use the following methods:
1. Use protected members
Declare private members as protected members. This allows derived classes and friend functions to access the member.
class MyClass { protected: int x; friend void printX(MyClass& obj) { std::cout << obj.x << std::endl; } };
2. Use proxy function
Create another class member function as a proxy for private members. This proxy function is publicly accessible for use by friend functions.
class MyClass { private: int x; public: int getX() const { return x; } friend void printX(MyClass& obj) { std::cout << obj.getX() << std::endl; } };
Practical case
In the following actual case, we have a Student
class, which has name
and score
Two private members. We want to create two friend functions printName()
and printScore()
to print these private members respectively.
class Student { private: std::string name; int score; friend void printName(Student& obj) { std::cout << "Name: " << obj.name << std::endl; } friend void printScore(Student& obj) { std::cout << "Score: " << obj.score << std::endl; } };
Using friend functions, we can easily print students' names and grades even though they are private members.
int main() { Student student; student.name = "John Doe"; student.score = 95; printName(student); printScore(student); return 0; }
Output:
Name: John Doe Score: 95
The above is the detailed content of Conflict between C++ friend functions and access control. For more information, please follow other related articles on the PHP Chinese website!