打算在主窗口中创建一个按钮,在CMyDlg类当中定义CButton对象/指针,出现如下问题:
1,在OnInitDialog()函数中采用如下代码:CButton btn;btn.Create()无法创建一个按钮,但是采用CButton* btn=new CButton;btn->Create()则可以创建。
2,但如果在CMyDlg类声明当中定义public:CButton btn;在OnInitDialog()中btn.Create()则可以成功创建按钮。
以上3中方法有什么区别,谢谢!

解决方案 »

  1.   

    1,在OnInitDialog()函数中采用如下代码:CButton btn;btn.Create()无法创建一个按钮,但是采用CButton* btn=new CButton;btn->Create()则可以创建。 
    这个是因为 你第一种方式 CButton btn 是创建在栈上 ,函数结束的时候  btn会销毁 ,btn销毁的时候 会调用destroywindow()
    2个同上   作为类成员变量的时候 ,CMyDlg对象在销毁的时候  public CButton btn 才会销毁,所以能创建成功
      

  2.   

    第一中方式  你这么写:
    CButton btn;btn.Create();
    btn.Detach();试试
      

  3.   

    按钮是一个对象,不能用局部变量对象来创建,用指针的方式因为申请了一个空间,只要你没有Delete它,这个内存一直存在,所以你能看到它可以创建,而用局部对象来创建的话,函数执行完后也就被析构掉了,如果作为一个类成员变量的话,只有在程序退出时才会被析构掉.
      

  4.   

    1,在OnInitDialog()函数中采用如下代码:CButton btn;btn.Create()无法创建一个按钮----------------------------------------------------------------------------
    In fact,In the first case, You really create a button successfully,but it is destroyed when OnInitialDlg() function return ,as you have created a temporary button object on the stack;In the second case , you create it successfully and it works well.That's because you new the object on the heap,it remains there until you make a free operation;In the last case,as the button object is a class member, it lasts in the whole life cycle of the CMydlg class.