Chinaunix首页 | 论坛 | 博客
  • 博客访问: 14839
  • 博文数量: 11
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 105
  • 用 户 组: 普通用户
  • 注册时间: 2013-08-08 14:28
文章分类

全部博文(11)

文章存档

2013年(11)

我的朋友

分类: C/C++

2013-08-22 20:59:15

Example 1:

点击(此处)折叠或打开

  1. #include <stdafx.h>
  2. #include <iostream>
  3. using namespace std;

  4. class Base{
  5. public:
  6.     void func(){
  7.         cout<<"Base::func"<<endl;
  8.         return;
  9.     }
  10. };
  11. class Derive:public Base{
  12. public:
  13.     void func(int c){
  14.         cout<<"Derive::func"<<endl;
  15.     }
  16. };
  17. int main(){
  18.     Derive x;
  19.     x.func(1);
  20.     x.func();//error
  21.     x.Base::func(); //ok
  22.     return 0;
  23. }


Example 2:

点击(此处)折叠或打开

  1. #include <stdafx.h>
  2. #include <iostream>
  3. using namespace std;

  4. class Base{
  5. public:
  6.     virtual void func(){
  7.         cout<<"Base::func"<<endl;
  8.         return;
  9.     }
  10. };
  11. class Derive:public Base{
  12. public:
  13.     void func(int c){
  14.         cout<<"Derive::func"<<endl;
  15.     }
  16. };
  17. int main(){
  18.     Base *p=new Derive();
  19.     p->func(); //print "Base::func"
  20.     p->func(1);//error
  21.     p->Derive::func(1) //error
  22.     return 0;
  23. }
上面两个例子中,派生类中重定义(不是重写)了基类的成员函数,造成覆盖,造成名字隐藏。即派生类对象不能直接调用父类的“被重定义”的成员函数;以派生类初始化的父类指针不能直接调用派生类成员函数
阅读(201) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~