操作符重载01--赋值运算符(Assignment Operator =)

一直对c++的操作符重载都迷迷糊糊,因为用的也少,有时间就系统的看看。

赋值运算符(=)使用非常频繁,就是将一个值或一个变量赋值给另外一个同类型或者相似类型的变量。我们自己写的类和结构体都会有四个默认函数(default functions)假如我们不定义的话:构造函数(default constructor)、拷贝构造函数(copy constructor)、析构函数(destructor)以及赋值运算符(assignment operator)。

测试code如下:

TRectangle.h

   1: #pragma once
   2:  
   3: //赋值运算符重载要点
   4: /*
   5: 1. 返回类的引用
   6: 2. 参数最好使用const修饰,最好也使用引用类型
   7: 3. 判断是不是本身赋值,尤其是有指针的情况
   8: 4. 如果是地址,不能直接地址赋值,而是应该另外copy一份
   9: */
  10: class TRectangle
  11: {
  12: public:
  13:     TRectangle(double dL = 0, double dH = 0);
  14:     TRectangle(TRectangle& R);
  15:     ~TRectangle(void);
  16:  
  17:     //method
  18:     void setLength(const double dL){ m_dLength = dL; }
  19:     void setHeight(const double dH){ m_dHeight = dH; }
  20:  
  21:     double getLength(){ return m_dLength; }
  22:     double getHeight(){ return m_dHeight; }
  23:  
  24:     //assignment operator
  25:     TRectangle& operator=(const TRectangle& R);
  26: private:
  27:     double m_dLength;
  28:     double m_dHeight;
  29: };
  30:  

TRectangle.cpp

   1: #include "StdAfx.h"
   2: #include "TRectangle.h"
   3:  
   4:  
   5: TRectangle::TRectangle(double dL, double dH) : 
   6: m_dLength(dL),
   7: m_dHeight(dH)
   8: {
   9: }
  10:  
  11: TRectangle::TRectangle(TRectangle& R) :
  12: m_dLength(R.m_dLength),
  13: m_dHeight(R.m_dHeight)
  14: {
  15: }
  16:  
  17: TRectangle::~TRectangle(void)
  18: {
  19: }
  20:  
  21: TRectangle& TRectangle::operator=(const TRectangle& R)
  22: {
  23:     if(this == &R) return (TRectangle&)R;
  24:     m_dLength = R.m_dLength;
  25:     m_dHeight = R.m_dHeight;
  26:     return *this;
  27: }

main()

   1: // AssignmentOperator.cpp : 定义控制台应用程序的入口点。
   2: //
   3:  
   4: #include "stdafx.h"
   5: #include <iostream>
   6: #include "TRectangle.h"
   7:  
   8:  
   9: int _tmain(int argc, _TCHAR* argv[])
  10: {
  11:     TRectangle Ra, Rb;
  12:     Ra.setLength(10);
  13:     Ra.setHeight(5);
  14:  
  15:     Rb.setLength(100);
  16:     Rb.setHeight(50);
  17:  
  18:     std::cout << "Rectangle A  Length is " << Ra.getLength() << ",Height is " << Ra.getHeight() << std::endl;
  19:     std::cout << "Rectangle B  Length is " << Rb.getLength() << ",Height is " << Rb.getHeight() << std::endl;
  20:  
  21:     Ra = Rb;
  22:     std::cout << "Rectangle A  Length is " << Ra.getLength() << ",Height is " << Ra.getHeight() << std::endl;
  23:  
  24:     return 0;
  25: }

结果如下:

image

转载于:https://www.cnblogs.com/maogeblog/archive/2012/09/12/2682061.html

评论将由博主筛选后显示,对所有人可见 | 还能输入1000个字符 “速评一下”
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页