一个关于类的对象和指向类的指针区别?

ghoster1985 2008-11-13 10:10:43
打算在主窗口中创建一个按钮,在CMyDlg类当中定义CButton对象/指针,出现如下问题:
1,在OnInitDialog()函数中采用如下代码:CButton btn;btn.Create()无法创建一个按钮,但是采用CButton* btn=new CButton;btn->Create()则可以创建。
2,但如果在CMyDlg类声明当中定义public:CButton btn;在OnInitDialog()中btn.Create()则可以成功创建按钮。
以上3中方法有什么区别,谢谢!
...全文
164 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
hurricane511 2008-11-13
  • 打赏
  • 举报
回复
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.
孤客天涯 2008-11-13
  • 打赏
  • 举报
回复
按钮是一个对象,不能用局部变量对象来创建,用指针的方式因为申请了一个空间,只要你没有Delete它,这个内存一直存在,所以你能看到它可以创建,而用局部对象来创建的话,函数执行完后也就被析构掉了,如果作为一个类成员变量的话,只有在程序退出时才会被析构掉.
samuellei 2008-11-13
  • 打赏
  • 举报
回复
1. 临时对象,
2. 动态创建
3. 类成员对象
应该从变量的生存期考虑
lijinfenghust 2008-11-13
  • 打赏
  • 举报
回复
第一中方式 你这么写:
CButton btn;btn.Create();
btn.Detach();试试
lijinfenghust 2008-11-13
  • 打赏
  • 举报
回复
1,在OnInitDialog()函数中采用如下代码:CButton btn;btn.Create()无法创建一个按钮,但是采用CButton* btn=new CButton;btn->Create()则可以创建。
这个是因为 你第一种方式 CButton btn 是创建在栈上 ,函数结束的时候 btn会销毁 ,btn销毁的时候 会调用destroywindow()
2个同上 作为类成员变量的时候 ,CMyDlg对象在销毁的时候 public CButton btn 才会销毁,所以能创建成功

15,980

社区成员

发帖
与我相关
我的任务
社区描述
VC/MFC 界面
社区管理员
  • 界面
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧