如何将这个简单的ruby脚本翻译成C ++?

时间:2011-10-19 23:38:27

标签: c++ ruby arrays

我有这样的代码:

class Container
  def initialize
    @container = []
  end

  def add(element)
    @container << element
  end

end

class Element
  def initialize(container)
    @container.add(self)
  end
end

c = Container.new
e1 = Element.new(c)
e2 = Element.new(c)

如何使用仅使用cstdio(无向量)在c ++中编写它(我的学校需要它)?

1 个答案:

答案 0 :(得分:3)

以下是一些提示。

class Element
{
    /* I don't know ruby but that separation of concerns is perverse. 
    Element does not need to know anything about Container.
    Nothing needed here. */
};

class Container 
{
    private:
        Element* c;
        unsigned int count;
    public:
        Container() { /* Research initialiser lists and complete this stub */ }
        ~Container(){ /* Dynamic memory must be freed */ }

        void Add(const Element& e) { 
            /* Does the container already have an item in it? 
            How will that affect an Add operation? */ 
        }
};

int main ()
{
    /*
        This should be easy ...
    */
}

/* Once you've finished this and have time for more, 
research the Rule of Three and fix the memory leak bug 
in the Container class */