设为首页 加入收藏

TOP

<三>关于重载 隐藏 覆盖(二)
2023-07-23 13:34:48 】 浏览:60
Tags:< > 关于重 隐藏 覆盖
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;

}
首页 上一页 1 2 下一页 尾页 2/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇哈夫曼应用 下一篇<七>深入理解new和delete的..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目