学学习网 手机版

学学习网

学习路径: 学习首页 > 应用开发 > c++ >

第六节 类(Classes)(10)

设置字体:
----------------------------------

如果没有明确写出访问限制,所有由关键字class 生成的类被默认为private ,而所有由关键字struct 生成的类被默认为public。
 
什么是从基类中继承的? (What is inherited from the base class?)
理论上说,子类(drived class)继承了基类(base class)的所有成员,除了:
  • 构造函数Constructor 和析构函数destructor
  • operator=() 成员
  • friends
虽然基类的构造函数和析构函数没有被继承,但是当一个子类的object被生成或销毁的时候,其基类的默认构造函数 (即,没有任何参数的构造函数)和析构函数总是被自动调用的。
如果基类没有默认构造函数,或你希望当子类生成新的object时,基类的某个重载的构造函数被调用,你需要在子类的每一个构造函数的定义中指定它:
derived_class_name (parameters) : base_class_name (parameters) {}
例如 (注意程序中黑体的部分):
    // constructors and derivated classes
    #include <iostream.h>
   
    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 cynthia (1);
        son daniel(1);
        return 0;
    }
                      
mother: no parameters
daughter: int parameter

mother: int parameter
son: int parameter
观察当一个新的daughter object生成的时候mother的哪一个构造函数被调用了,而当新的son object生成的时候,又是哪一个被调用了。不同的构造函数被调用是因为daughter 和 son的构造函数的定义不同:
   daughter (int a)          // 没有特别制定:调用默认constructor
   son (int a) : mother (a)  // 指定了constructor: 调用被指定的构造函数
  
 
多重继承(Multiple inheritance)
在C++ 中,一个class可以从多个class中继承属性或函数,只需要在子类的声明中用逗号将不同基类分开就可以了。例如,如果我们有一个特殊的class COutput 可以实现向屏幕打印的功能,我们同时希望我们的类CRectangle 和 CTriangle 在CPolygon 之外还继承一些其它的成员,我们可以这样写:
class CRectangle: public CPolygon, public COutput {
class CTriangle: public CPolygon, public COutput {
以下是一个完整的例子:
    // multiple inheritance
    #include <iostream.h>
   
    class CPolygon {
      protected:
        int width, height;
      public:
        void set_values (int a, int b)
          { width=a; height=b;}
    };
   
    class COutput {
      public:
        void output (int i);
    };
   
    void COutput::output (int i) {
        cout << i << endl;
    }
   
    class CRectangle: public CPolygon, public COutput {
      public:
        int area (void)
          { return (width * height); }
    };
   
    class CTriangle: public CPolygon, public COutput {
      public:
        int area (void)
          { return (width * height / 2); }
    };
   
    int main () {
        CRectangle rect;
        CTriangle trgl;
        rect.set_values (4,5);
        trgl.set_values (4,5);
        rect.output (rect.area());
        trgl.output (trgl.area());
        return 0;
    }
                      
20
10
 
----------------------------------
课程列表
重点难点
赞助链接