MichaelBlog

double i = Double.MAX_VALUE; while(i == i + 1){ System.out.print ("学无止境");};

导航

C++: 面向对象之继承特性

类之间的继承关系
在c++可以扩展类,创建新类的保留特性的基类。 这个过程被称为继承,涉及到一个 基类base class(父类) 和一个 派生类 derived class(子类) : 派生类 继承的成员 基类 ,它可以添加自己的成员。
在这里插入图片描述
如图所示,图形是基类(父类),圆形和三角继承了图形类为派生类(子类)
派生类名: public 基类名
{/ *…… * /};

// derived classes
#include <iostream>
using namespace std;

class Polygon {
  protected:
    int width, height;
  public:
    void set_values (int a, int b)
      { width=a; height=b;}
 };

class Rectangle: public Polygon {
  public:
    int area ()
      { return width * height; }
 };

class Triangle: public Polygon {
  public:
    int area ()
      { return width * height / 2; }
  };
  
int main () {
  Rectangle rect;
  Triangle trgl;
  rect.set_values (4,5);
  trgl.set_values (4,5);
  cout << rect.area() << '\n';
  cout << trgl.area() << '\n';
  return 0;
}

访问权限

访问publicprotectedprivate
同一个类的成员yesyesyes
派生类的成员yesyesno
不是成员yesnono

例如

class 三角: public 图形 { /* ... */ }
class Daughter: protected Mother;

子类访问父类

  • 不能访问父类构造函数和析构函数
  • 不能访问赋值运算符成员(操作符=)
  • 不能访问父类的友元 friend
  • 不能访问父类私有成员 private

尽管访问基类的构造函数和析构函数不是继承关系,但它们会自动调用派生类的构造函数和析构函数。

除非另有规定,派生类的构造函数调用基类的默认构造函数(即:不带参数的构造函数)。 调用不同的基类构造函数是可行的,使用相同的语法用于在初始化列表中初始化成员变量:

derived_constructor_name(参数):base_constructor_name(参数){…}

// constructors and derived classes
#include <iostream>
using namespace std;

class Mother {
  public:
    Mother ()//默认调用不带参数的构造函数
      { cout << "Mother: no parameters\n"; }
    Mother (int a)
      { cout << "Mother: int parameter\n"; }
};

class Daughter : public Mother {
  public:
    Daughter (int a)
      { cout << "Daughter: int parameter\n\n"; }
};

class Son : public Mother {
  public:
    Son (int a) : Mother (a)
      { cout << "Son: int parameter\n\n"; }
};

int main () {
  Daughter kelly(0);
  Son bud(0);
  
  return 0;
}
执行结果:
Mother: no parameters
Daughter: int parameter

Mother: int parameter
Son: int parameter

多重继承

Java多级继承,不能多重继承
C++可以多重继承

class Rectangle: public Polygon, public Output;
class Triangle: public Polygon, public Output;

// multiple inheritance
#include <iostream>
using namespace std;

class Polygon {
  protected:
    int width, height;
  public:
    Polygon (int a, int b) : width(a), height(b) {}
};

class Output {
  public:
    static void print (int i);
};

void Output::print (int i) {
  cout << i << '\n';
}

class Rectangle: public Polygon, public Output {
  public:
    Rectangle (int a, int b) : Polygon(a,b) {}
    int area ()
      { return width*height; }
};

class Triangle: public Polygon, public Output {
  public:
    Triangle (int a, int b) : Polygon(a,b) {}
    int area ()
      { return width*height/2; }
};
  
int main () {
  Rectangle rect (4,5);
  Triangle trgl (4,5);
  rect.print (rect.area());
  Triangle::print (trgl.area());
  return 0;
}

posted on 2022-04-16 09:47  Michael_chemic  阅读(40)  评论(0编辑  收藏  举报