鱼C论坛

 找回密码
 立即注册
查看: 3065|回复: 2

重载赋值操作符和副本构造器的问题,去掉 const 关键词就正常了,为啥?

[复制链接]
发表于 2012-10-19 18:23:53 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
  1. # include <iostream>
  2. # include <string>

  3. using namespace std;

  4. struct Keyboard
  5. {
  6.         string m_clavier;
  7.         string m_mouse;
  8. };

  9. class Comstru
  10. {
  11. public:
  12.         Comstru();
  13.         Comstru(const Comstru& com);

  14.         Comstru& operator =(const Comstru& com);
  15.         Keyboard* getKeyboard();

  16. protected:
  17.         Keyboard* m_pKeyboard;
  18.         string m_strmodel;
  19. };

  20. Comstru::Comstru()
  21. {
  22.         m_pKeyboard = new Keyboard;
  23. }

  24. Comstru::Comstru(const Comstru& com)
  25. {
  26.         *this = com;
  27. }

  28. Keyboard* Comstru::getKeyboard()
  29. {
  30.         return m_pKeyboard;
  31. }

  32. Comstru& Comstru::operator =(const Comstru& com)
  33. {
  34.         if (this != &com)
  35.         {
  36.                 m_strmodel = com.m_strmodel;
  37.                 m_pKeyboard = new Keyboard( *(com.getKeyboard()) );
  38.         }
  39.        
  40.         return *this;
  41. }

  42. int main()
  43. {
  44.         Comstru p1;

  45.         (*(p1.getKeyboard())).m_clavier = "键盘";
  46.         (*(p1.getKeyboard())).m_mouse = "鼠标";
  47.        
  48.         Comstru p2(p1);
  49.         (*(p2.getKeyboard())).m_mouse = "鼠标222";
  50.         cout << (*(p1.getKeyboard())).m_clavier << endl;
  51.         cout << (*(p1.getKeyboard())).m_mouse << endl;

  52.         return 0;
  53. }
复制代码
去掉const 关键词就正常了,为啥?
小甲鱼最新课程 -> https://ilovefishc.com
 楼主| 发表于 2012-10-19 19:02:16 | 显示全部楼层
我顶{:1_1:}
小甲鱼最新课程 -> https://ilovefishc.com
 楼主| 发表于 2012-10-20 12:12:15 | 显示全部楼层
找到原因了,const调用了非const函数,第46行那里调用了非const的getKeyboard()函数,改成m_pKeyboard 属性就可以了。
小甲鱼最新课程 -> https://ilovefishc.com
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-11-15 18:24

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表