代码之家  ›  专栏  ›  技术社区  ›  Patrick Oscity

使用抽象类来实现派生类的一组元素

  •  0
  • Patrick Oscity  · 技术社区  · 16 年前

    我必须在大学里做一个基本的C++讲座,所以要明确一点:如果允许的话,我会使用STL。

    15    // more stuff
    16    
    17        shape3d_stack::shape3d_stack (unsigned size) :
    18         array_ (NULL),
    19         count_ (0),
    20         size_  (size)
    21        { array_ = new shape3d[size]; }
    22    
    23    // more stuff
    

    g++ -Wall -O2 -pedantic -I../../UnitTest++/src/ -c shape3d_stack.cpp -o shape3d_stack.o
    shape3d_stack.cpp: In constructor ‘shape3d_stack::shape3d_stack(unsigned int)’:
    shape3d_stack.cpp:21: error: cannot allocate an object of abstract type ‘shape3d’
    shape3d.hpp:10: note:   because the following virtual functions are pure within ‘shape3d’:
    shape3d.hpp:16: note:  virtual double shape3d::area() const
    shape3d.hpp:17: note:  virtual double shape3d::volume() const
    

    5 回复  |  直到 16 年前
        1
  •  7
  •   Georg Fritzsche    16 年前

    不能从抽象类创建对象。
    您可能希望创建一个指向抽象类的指针数组(这是允许的),并用派生实例填充它们:

    // declaration somewhere:
    shape3d** array_;
    
    // initalization later:
    array_ = new shape3d*[size];
    
    // fill later, triangle is derived from shape3d:
    array_[0] = new triangle;
    
        2
  •  3
  •   David Seiler    16 年前

    array_ = new shape3d[size];
    

    一般来说,要使用多态性和虚函数,您需要使用间接性:指针和/或引用,而不是文字对象。shape3d*可能指向立方体或球体,但shape3d始终是shape3d,而不是shape3d的子类。

        3
  •  0
  •   coppro    16 年前

    shape3d 是一个抽象基类,您可能希望堆栈存储指向的指针 shape3d ,而不是实际的物体。

        4
  •  0
  •   naumcho    16 年前

        5
  •  0
  •   Jerry Coffin    16 年前

    你需要创建一堆指向对象的指针,而不是一堆对象。