设为首页 加入收藏

TOP

8.4.3 重载赋值运算符(2)
2013-10-07 16:07:49 来源: 作者: 【 】 浏览:51
Tags:8.4.3 重载 运算

8.4.3  重载赋值运算符(2)

现在的情况是,从函数operator=()返回的对象用来调用operator=()函数。如果返回类型仅仅是CMessage,则该语句是不合法的,因为实际返回的是原始对象的临时副本,它是rvalue,编译器不允许使用rvalue调用成员函数。确保此类语句能够正确编译和工作的唯一方法是返回一个引用,它是lvalue,因此如果希望实现使用赋值运算符处理类对象的灵活性,则唯一可能的返回类型是CMessage&。

注意,C++(www.cppentry.com)语言对赋值运算符的形参和返回类型没有任何限制,但如果希望自己的赋值运算符函数支持常规的赋值用法,那么以刚才描述的方式声明赋值运算符就具有现实意义。

第二点微妙之处是,两个对象都已经拥有为字符串分配的内存,因此赋值运算符函数首先要删除分配给第一个对象的内存,然后重新分配足够的内存,以容纳属于第二个对象的字符串。做完这件事之后,就可以将来自第二个对象的字符串复制到第一个对象现在拥有的新内存中。

该运算符函数中仍然存在缺点。如果写出下面这条语句,那么将发生什么事情呢?

  1. motto1motto1 = motto1; 

显然,我们不会直接那样做,但此类现象很容易隐藏在指针的背后,就像在下面的语句中的那样:

  1. Motto1 = *pMessage; 

如果指针pMessage指向motto1,那么实质上这是前面那条赋值语句。这种情况下,目前的赋值运算符函数将释放供motto1使用的内存,然后基于已删除的字符串的长度另外分配一些内存,并试图复制当时很可能已经被破坏的旧内存。通过在函数的开头检查左右操作数是否相同,就可以修正上述问题,因此现在operator=()函数的定义将如下所示:

  1. // Overloaded assignment operator for CMessage objects  
  2. CMessage& operator=(const CMessage& aMess)  
  3. {  
  4. if(this != &aMess)                          // Check addresses are not equal  
  5. {  
  6. // Release memory for 1st operand  
  7. delete[] pmessage;  
  8. pmessage = new char[strlen(aMess.pmessage) + 1];  
  9. // Copy 2nd operand string to 1st  
  10. strcpy_s(this->pmessage, strlen(aMess.pmessage)+1, aMess.pmessage);  
  11. }  
  12. // Return a reference to 1st operand  
  13. return *this;  
  14. }  

试一试:重载赋值运算符

下面将完整的operator=()函数代码放在可运行的示例中,同时还向CMessage类中添加一个Reset()成员函数。该函数的作用仅是将消息重新设置为星号字符串。

  1. // Ex8_05.cpp  
  2. // Overloaded assignment operator working well  
  3. #include <iostream> 
  4. #include <cstring> 
  5. using std::cout;  
  6. using std::endl;  
  7. class CMessage  
  8. {  
  9. private:  
  10. char* pmessage;                                                                             // Pointer to object text string  
  11. public:  
  12. // Function to display a message  
  13. void ShowIt() const  
  14. {  
  15. cout << endl << pmessage;  
  16. }  
  17. //Function to reset a message to *  
  18. void Reset()  
  19. {  
  20. char* temp = pmessage;  
  21. while(*temp)  
  22. *(temp++) = '*';  
  23. }  
  24. // Overloaded assignment operator for CMessage objects  
  25. CMessage& operator=(const CMessage& aMess)  
  26. {  
  27. if(this != &aMess)                              // Check addresses are not equal  
  28. {  
  29. // Release memory for 1st operand  
  30. delete[] pmessage;  
  31. pmessage = new char[strlen(aMess.pmessage) + 1];  
  32. // Copy 2nd operand string to 1st  
  33. strcpy_s(this->pmessage, strlen(aMess.pmessage) + 1, aMess.pmessage);  
  34. }  
  35. // Return a reference to 1st operand  
  36. return *this;  
  37. }  
  38. // Constructor definition  
  39. CMessage(const char* text = "Default message")  
  40. {  
  41. pmessage = new char[strlen(text) + 1];        // Allocate space for text  
  42. strcpy_s(pmessage, strlen(text)+1, text);    // Copy text to new memory  
  43. }  
  44. // Copy constructor definition  
  45. CMessage(const CMessage& aMess)  
  46. {  
  47. size_t len = strlen(aMess.pmessage)+1;  
  48. pmessage = new char[len];  
  49. strcpy_s(pmessage, len, aMess.pmessage);  
  50. }  
  51. // Destructor to free memory allocated by new  
  52. ~CMessage()  
  53. {  
  54. cout << "Destructor called."                   // Just to track what happens  
  55. << endl;  
  56. delete[] pmessage;                               // Free memory assigned to pointer  
  57. }  
  58. };  
  59. int main()  
  60. {  
  61. CMessage motto1("The devil takes care of his own");  
  62. CMessage motto2;  
  63. cout << "motto2 contains - ";  
  64. motto2.ShowIt();  
  65. cout << endl;  
  66. motto2 = motto1;                                                // Use new assignment operator  
  67. cout << "motto2 contains - ";  
  68. motto2.ShowIt();  
  69. cout << endl;  
  70. motto1.Reset();                                                 // Setting motto1 to * doesn't  
  71. // affect motto2  
  72. cout << "motto1 now contains - ";  
  73. motto1.ShowIt();  
  74. cout << endl;  
  75. cout << "motto2 still contains - ";  
  76. motto2.ShowIt();  
  77. cout << endl;  
  78. return 0;  
  79. }  

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇8.4.3 重载赋值运算符(1) 下一篇8.4.3 重载赋值运算符(3)

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·python数据分析岗的 (2025-12-25 10:02:21)
·python做数据分析需 (2025-12-25 10:02:19)
·成为一个优秀的pytho (2025-12-25 10:02:16)
·Java后端面试实习自 (2025-12-25 09:24:21)
·Java LTS版本有哪些 (2025-12-25 09:24:18)