代码之家  ›  专栏  ›  技术社区  ›  jack-london

构造注入

c++
  •  2
  • jack-london  · 技术社区  · 17 年前

    我知道代码不见了(有人会给出负数)。但我只想知道在这种情况下如何解决构造函数注入问题?

    class PresenterFactory
    {
    public:
      template<class TModel>
        AbstractPresenter<TModel>*
        GetFor(AbstractView<TModel> * view)
        {
          return new PresenterA(view, new FakeNavigator());
        }
    };
    
    class ViewA : public AbstractView<ModelA>
    {
      static PresenterFactory factory;
    public:
      ViewA(AbstractPresenter<ModelA> *presenter = factory.GetFor<ModelA>(this)) :
        AbstractView<ModelA> (presenter)
      {
      }
    
      // this one is also not working
      // invalid use of ‘class ViewA’
      //  ViewA()
      //  {
      //    this->ViewA(factory.GetFor<ModelA> (this));
      //  }
    };
    
    2 回复  |  直到 11 年前
        1
  •  4
  •   Kirill V. Lyadvinsky    17 年前

    为什么不使用两个构造函数?

    // constructor with one argument
    ViewA(AbstractPresenter<ModelA> *presenter) : AbstractView<ModelA> (presenter)
    {
    }
    
    // constructor without arguments
    ViewA() : AbstractView<ModelA>(factory.GetFor<ModelA>(this))
    {
    }
    

    顺便说一句, this 指针仅在非静态成员函数中有效。它不应在基类的初始值设定项列表中使用。在该构造函数之前调用基类构造函数和类成员构造函数。实际上,您已经将指向未构造对象的指针传递给了另一个构造函数。如果其他构造函数访问任何成员或对此调用成员函数,则结果将未定义。在所有构造完成之前,不应使用此指针。

        2
  •  0
  •   Chigulla    11 年前
    public class ConstEx {
    
        String name;
        Integer id;
        public ConstEx(String name, Integer id) {
    
            System.out.println("--------Constructor Firs -------");
        }
    
        public ConstEx(Integer id,String name) 
        {
            System.out.println("-----Second Constructor--------");
        }
    }
    
    
    
    
    with th Following Configuration in xml
    
    <bean id="const1" class="com.spring.hari.springexample.ConstEx">
            <constructor-arg type="java.lang.Integer" >
                <value>10</value>
            </constructor-arg>
            <constructor-arg type="java.lang.String" >
                <value>100</value>
            </constructor-arg>
        </bean>
    
    
    Why First Constructor is called since i have mentioned the types even than it is calling first constructor