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 << std::endl; // Accessing private member of Base
}
};
class Base {
private:
void printValue() {
std::cout << "Value from Base" << std::endl;
}
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++中的友元类在多态中的应用主要是为了解决访问私有和保护成员的问题。通过将派生类声明为基类的友元类,我们可以在派生类中访问基类的私有和保护成员,从而实现特定的功能。