如果在基类中虚函数的访问权限是一种情况,那么派生类在继承基类的时候,派生类可以重新定义基类虚函数的访问权限,经过实例验证是正确的。
从这里也说明了函数的覆盖或者说重定义跟前面的访问权限修饰没多大关系
//Base.h
#pragma once #include <iostream> using namespace std; class Base { public: Base(void){} ~Base(void){} virtual void fun(){cout<<"This is Base::fun"<<endl;} virtual void func()=0; };
//Son.h
#pragma once #include "base.h" class Son :public Base { public: Son(void){} ~Son(void){} virtual void fun(){cout<<"This is a son function"<<endl;} protected: virtual void func(){cout<<"what a fuck day it is"<<endl;} };
//T.h
#pragma once #include "son.h" class T : public Son { public: T(void){} ~T(void){} void xy() { Base *b = new Son(); b->func(); } };
//main.cpp
#include "testInline.h" #include "Son.h" #include "T.h" void main() { Base* pB; Son* pS = new Son(); pB = pS; pB->fun(); T tst; tst.xy(); }
结果:
This is a son function
what a fuck day it is
时间: 2024-10-15 10:23:11