mp;d;
pb->show(); //调用的是基类的 show
pb->show(100);//调用的是基类的 show(int)
((Derive *)pb)->show(); //强转后 调用的是派生类的 show
}
基类指针(引用) -> 派生类对象 类型由上向下转 NOT OK
Base b(10);
Derive d(20);
Derive *pb =&b;// NOT OK pb指针能够访问的区域超过了实际对象b的内存块 ,危险访问
代码4
#include <iostream>
using namespace std;
class Base{
public:
Base(){
cout<<"Base()"<<endl;
}
void show(){
cout<<"Base show()"<<endl;
}
void show(int x){
cout<<"Base show(int x)"<<endl;
}
~Base(){
cout<<"~Base()"<<endl;
}
private:
int ma;
};
class Derive :public Base{
public:
Derive(){
cout<<"Derive()"<<endl;
}
void show(){
cout<<"Derive show()"<<endl;
}
~Derive(){
cout<<"~Derive()"<<endl;
}
private:
int ma;
};
int main(){
Derive d;
Derive *pd=&d;
d.show();
d.show(100); //编译报错, Derive 的void show()方法把Base 的void show() void show(int x) 都隐藏了
pd->show(100);//编译报错 Derive 的void show()方法把Base 的void show() void show(int x) 都隐藏了
return 0;
}
代码5
#include <iostream>
using namespace std;
class Base{
public:
Base(){
cout<<"Base()"<<endl;
}
virtual void show(){
cout<<"Base show()"<<endl;
}
void show(int x){
cout<<"Base show(int x)"<<endl;
}
~Base(){
cout<<"~Base()"<<endl;
}
private:
int ma;
};
class Derive :public Base{
public:
Derive(){
cout<<"Derive()"<<endl;
}
virtual void show(){
cout<<"Derive show()"<<endl;
}
~Derive(){
cout<<"~Derive()"<<endl;
}
private:
int ma;
};
int main(){
Derive *pd=new Derive();
pd->show(100); //编译报错,Derive 中的show() 函数,只要名字与Base中有相同名字的函数的,就会隐藏掉Base中所有的show方法(不管加不加virtual),包括void show() void show(int x)
return 0;
}