#include <iostream>
class Derived;
void func(Derived& d);
class Base{
private:
int _BaseVar2 ;
protected:
int _BaseVar1 ;
public:
virtual int getID() = 0;
};
class Derived : public Base {
private:
int DerivedVar2 ;
int DerivedVar1 ;
protected:
public:
Derived():Base(),DerivedVar1(1),DerivedVar2(2){}
virtual int getID(){
return _BaseVar1;
}
friend void func(Derived& d);
};
void func(Derived& d){
std::cout << "DerivedVar1 : " << d.DerivedVar1 << std::endl;
//friend can access all member .
std::cout << "_BaseVar1 : " << d._BaseVar1 << std::endl;
//std::cout << "_BaseVar2 : " << d._BaseVar2 << std::endl;
//inherit can access protected member .
return ;
}
int main(){
Derived d{};
func(d);
return 0;
}
func
函数可以访问 Derived 的所有成员(friend 关键字的特性)
func
函数 不可访问Base的private 成员(继承的特性)_BaseVar2
func
函数 可访问Base的protected成员(public继承的特性)_BaseVar1