c++-派生类与继承.pptVIP

  • 0
  • 0
  • 约1.38万字
  • 约 42页
  • 2021-10-24 发布于浙江
  • 举报
class Base { public: Base(int i) { x=I; cout “Constructing base class\n”; } ~Base() { cout “Destructing base class\n”; } void show() { cout xendl; } private: int x; }; class Derived:public Base {public: Derived(int i):Base(i),d(i) { cout “ Constructing derived class\n”} ~Derived() { cout “Destructing derived class\n” } private: Base d; } int main() { Derived obj(5); obj.show(); return 0; } Constructing base class Constructing base class Constructing derived class 5 Destructing derived class Destructing base class Destructing base class 第三十一页,共42页。 4.3 调整基类成员在派生类中的访问属性(shǔxìng)的其他方法 4.3.1 同名成员 派生类中定义了与基类成员同名的成员,则派生类成员覆盖(fùgài)了基类的同名成员,在派生类中使用这个名字意味着访问在派生类中重新说明的成员. 为了能够使用基类的同名成员,必须采用如下形式: 基类名::成员名 第三十二页,共42页。 class A { public: A(int x1) { x=x1; } void print() { cout “x=“xendl;; } private: int x; }; class B:public A { public: B(int x1,int y1):A(x1) { y=y1 } void print() { A::print(); cout “y=“yendl; } private: int y; } int main() { B b(10,20); b.print2(); return 0; } X=10 第三十三页,共42页。 说明: 在面向对象程序设计中,若要在派生类中对基类继承过来的某些函数功能进行(jìnxíng)扩充和改造,都可以采用这样覆盖的方法实现. 第三十四页,共42页。 4.3.2 访问声明 访问声明的方法是把基类的保护成员或公有成员直接写至私有派生类定义(dìngyì)式中的同名段中,同时给成员名前加以基类名和作用域标识符::.利用这种方法,该成员就成为派生类的保护成员或公有成员了. 第三十五页,共42页。 class A { public: A(int x1) { x=x1; } void print() { cout “x=“x; } private: int x; }; class B:private A { public: B(int x1,int y1):A(x1) { y=y1 } void print2() { print(); } private: int y; } int main() { B b(10,20); b.print2(); return 0; } X=10 第三十六页,共42页。 class A { public: A(int x1) { x=x1; } void print() { cout “x=“x; } private: int x; }; class B:private A { public: B(int x1,int y1):A(x1)

文档评论(0)

1亿VIP精品文档

相关文档