Example 1:
-
#include <stdafx.h>
-
#include <iostream>
-
using namespace std;
-
-
class Base{
-
public:
-
void func(){
-
cout<<"Base::func"<<endl;
-
return;
-
}
-
};
-
class Derive:public Base{
-
public:
-
void func(int c){
-
cout<<"Derive::func"<<endl;
-
}
-
};
-
int main(){
-
Derive x;
-
x.func(1);
-
x.func();//error
-
x.Base::func(); //ok
-
return 0;
-
}
Example 2:
-
#include <stdafx.h>
-
#include <iostream>
-
using namespace std;
-
-
class Base{
-
public:
-
virtual void func(){
-
cout<<"Base::func"<<endl;
-
return;
-
}
-
};
-
class Derive:public Base{
-
public:
-
void func(int c){
-
cout<<"Derive::func"<<endl;
-
}
-
};
-
int main(){
-
Base *p=new Derive();
-
p->func(); //print "Base::func"
-
p->func(1);//error
-
p->Derive::func(1) //error
-
return 0;
-
}
上面两个例子中,派生类中重定义(不是重写)了基类的成员函数,造成覆盖,造成名字隐藏。即派生类对象不能直接调用父类的“被重定义”的成员函数;以派生类初始化的父类指针不能直接调用派生类成员函数
阅读(217) | 评论(0) | 转发(0) |