我的代码-
class base{
private:
virtual void print(){
cout<<" from base"<<endl;
}
friend void show(base &obj);
};
class drived1 : public base{
private:
void print(){
cout<<" from drived1"<<endl;
}
};
class drived2 : public base{
private:
void print(){
cout<<" from drived2"<<endl;
}
};
void show(base &obj){
obj.print();
}
int main() {
base b;
drived1 d1;
drived2 d2;
show(b);
show(d1);
show(d2);
}
输出:
from base
from drived1
// 打印函数形式的派生类被调用,尽管它是私有的。
from drived2
// 打印函数形式的派生类被调用,尽管它是private。
show(base &obj)
是基类的朋友函数,但是它如何从派生类调用私有方法?
这就是C ++的工作方式。访问说明符(public
,private
和protected
)取决于变量的静态类型,而不是动态类型。在您的示例中
void show(base &obj){
obj.print();
}
编译后,编译器不知道将使用drived1
参数调用该函数。它知道obj
类型base&
,因此只检查它是否可以调用base::print()
-之所以可以调用,因为它是friend
of的base
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句