【问题标题】:Using an abstract class to implement a stack of elements of the derived class使用抽象类实现派生类的一堆元素
【发布时间】:2010-12-08 03:44:40
【问题描述】:

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

问题:我有一个名为“shape3d”的类,从中派生了“cube”和“sphere”类。现在我必须实现“shape3d_stack”,这意味着能够保存“立方体”和“球体”类型的对象。我为此使用了数组,当我尝试使用一堆整数时它工作得很好。我试着这样做:

shape3d_stack.cpp:

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

我想这一定是我自己造成的某种非常丑陋的设计错误。那么在我的堆栈中使用从“shape3d”派生的各种对象的正确方法是什么?

【问题讨论】:

    标签: c++ stack virtual abstract-class derived-class


    【解决方案1】:

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

    // declaration somewhere:
    shape3d** array_;
    
    // initalization later:
    array_ = new shape3d*[size];
    
    // fill later, triangle is derived from shape3d:
    array_[0] = new triangle;
    

    【讨论】:

      【解决方案2】:

      线

      array_ = new shape3d[size];
      

      分配一个 shape3d 对象数组。不是立方体,不是球体,只是普通的旧 shape3d。但不可能创建一个 shape3d 对象,因为它是抽象的。

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

      【讨论】:

        【解决方案3】:

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

        【讨论】:

          【解决方案4】:

          您不能创建抽象类的新数组。你可以做的是将它声明为一个指针数组,然后当你知道它是哪种类型的形状时,你可以分配你选择的派生类的对象。

          【讨论】:

            【解决方案5】:

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

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2012-03-14
              • 1970-01-01
              • 2021-05-17
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多