返回 動漫遊戲

懂電腦程式語言的..救救我吧!

JAVA老師出了一個期末考題.."何謂虛擬建構子?"
要解釋並且找一段程式來說明物件的特性...
我找網路上的資料..好少阿..
還有找書..書中都只有提到虛擬函數..沒有直接提到虛擬建構子...
有好心人是可以救我一下嘛??謝謝...
  • 地瓜球你老公好神氣喔!
  • this  is  c++  code  style  sample
    it  describes  how  to  use  virtual  constructors
    simply
    virtual  constructors  means  a  function  that
      can  "make"  a  class  instance
    but  not  a  constructor
     
    ---------------------------------------------

    欲做出虛擬建構子的效果,可用個虛擬的  "createCopy()"  成員函數(用來做為拷貝
    建構子),或是虛擬的  "createSimilar()"  成員函數(用來做為預設建構子)。

                    class  Shape  {
                    public:
                        virtual  ~Shape()  {  }                    //詳見  "virtual  destructors"
                        virtual  void  draw()  =  0;
                        virtual  void  move()  =  0;
                        //...
                        virtual  Shape*  createCopy()  const  =  0;
                        virtual  Shape*  createSimilar()  const  =  0;
                    };

                    class  Circle  :  public  Shape  {
                    public:
                        Circle*  createCopy()        const  {  return  new  Circle(*this);  }
                        Circle*  createSimilar()  const  {  return  new  Circle();  }
                        //...
                    };

    執行了  "Circle(*this)"  也就是執行了拷貝建構的行為(在這些運作行為中,
    "*this"  的型態為  "const  Circle&")。"createSimilar()"  亦類似,但它乃建構出
    一個“預設的”Circle。

    這樣用的話,就如同有了「虛擬建構子」(virtual  constructors):

                    void  userCode(Shape&  s)
                    {
                        Shape*  s2  =  s.createCopy();
         
回應...
 返回 動漫遊戲