C++中的友元類(friend class)是一種特殊的類關系,允許一個類訪問另一個類的私有(private)和保護(protected)成員
在多態(tài)中,友元類可以用于以下場景:
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++中的友元類在多態(tài)中的應用主要是為了解決訪問私有和保護成員的問題。通過將派生類聲明為基類的友元類,我們可以在派生類中訪問基類的私有和保護成員,從而實現(xiàn)特定的功能。