阅读量:57
C++中的友元类(friend class)是一种特殊的类关系,允许一个类访问另一个类的私有(private)和保护(protected)成员
在多态中,友元类可以用于以下场景:
- 访问私有和保护成员:在多态中,我们可能需要访问基类的私有或保护成员,以便在派生类中实现特定的功能。通过将派生类声明为基类的友元类,我们可以访问这些私有和保护成员。
class Base {
private:
int value;
friend class Derived; // Derived is a friend of Base
};
class Derived : public Base {
public:
void printValue() {
std::cout << "Value: " << value class="hljs-comment">// Accessing private member of Base
}
};
- 调用私有和保护成员函数:有时,我们需要在派生类中调用基类的私有或保护成员函数。通过将派生类声明为基类的友元类,我们可以访问这些函数。
class Base {
private:
void printValue() {
std::cout << "Value from Base" << std class="hljs-keyword">friend class Derived; // Derived is a friend of Base
};
class Derived : public Base {
public:
void callBaseFunction() {
printValue(); // Accessing private member function of Base
}
};
- 实现运算符重载:有时,我们需要为自定义类型实现运算符重载,以便在多态中使用。为了访问参与运算符重载的类的私有和保护成员,我们可以将另一个类声明为该类的友元类。
class Complex {
private:
double real;
double imag;
friend class ComplexOperator; // ComplexOperator is a friend of Complex
};
class ComplexOperator {
public:
Complex operator+(const Complex& other) {
double newReal = this->real + other.real;
double newImag = this->imag + other.imag;
return Complex(newReal, newImag);
}
};
总之,C++中的友元类在多态中的应用主要是为了解决访问私有和保护成员的问题。通过将派生类声明为基类的友元类,我们可以在派生类中访问基类的私有和保护成员,从而实现特定的功能。