即日起在codingBlog上分享您的技术经验即可获得积分,积分可兑换现金哦。

C++运算符重载学习与进阶学习与进阶笔记

编程语言 u013043762 13℃ 0评论
#include
using namespace std;
class Complex1
{
private: int a, b;
public:
    Complex1(Complex1 &obj){
        this->a = obj.getA();
        this->b = obj.getB();
        cout << "我是copy 构造函数" << "a:" << a << "\t b:" << b << endl;
    }
    Complex1(int a = 0, int b = 0)
    {
        this->a = a;
        this->b = b;
    }
    int getA(){
        return a;
    }
    int getB(){
        return b;
    }
    void show(){
        cout << "a:" << a << "\t b:" << b << endl;
    }
    friend Complex1 operator+(Complex1 &c1, Complex1 &c2);
    friend Complex1 operator++(Complex1 &c1);
     Complex1 operator-(Complex1 &c1)
    {
        Complex1 tmp;
        tmp.a = this->a - c1.a;
        tmp.b = this->b - c1.b;
        return tmp; 
    }
     Complex1 operator --(){
         this->a--;
         this->b--;
         return *this;
     }
     //全局函数 后置 ++ 
     friend Complex1 operator++(Complex1 &c2, int);

};

//全局函数后置++ 
Complex1 operator ++ (Complex1 &c2, int)
{
    //先使用C2 的属性,然后让属性++ 
    Complex1 tmp;
    tmp = c2;
    c2.a++;
    c2.b++;
    return tmp;

}

//Complex1 ComAdd(Complex1 &c1, Complex1 &c2)
//{
//  Complex1 tmp;
//  tmp.a = c1.a + c2.a;
//  tmp.b = c1.b + c2.b;
//  return tmp;
//}
Complex1 operator+(Complex1 &c1, Complex1 &c2)
{
    Complex1 tmp;
    tmp.a = c1.a + c2.a;
    tmp.b = c1.b + c2.b;
    return tmp;
}
Complex1 operator ++(Complex1 &c1)
{
    c1.a++;
    c1.b++;
    return c1;
}

//void mainhanshu()
//{
//  Complex1 c1(1, 2), c2(2, 3);
//  Complex1 c3 = ComAdd(c1, c2);
//  c3.show();
//  system("pause");
//}
Complex1 g(){
    Complex1 c1;
    return c1;
}
void main(){
    Complex1 c1(10, 20), c2(3, 4);
    //+ 运算符有两个参数 左操作数 和 右操作数 
    // 
    Complex1 c3 = c1.operator-(c2);
    c3.show();
    //目标 通过类的成员函数,完成操作符重载
    //1 要承认操作符重载是一个函数,要写函数原型
    //2 写出函数条用语言 c1.operator-(c2) 
    //3 完善函数原型
    c3++;
    c3.show();
    c3--; 
    c3.show();
    c3.operator--();

    c3.show();

    --c3;
    c3.show(); 

    //检查后置++ 
    Complex1 c4 = c3++; 
    c4.show();
    c3.show();

    system("pause");
}

转载请注明:CodingBlog » C++运算符重载学习与进阶学习与进阶笔记

喜欢 (0)or分享 (0)
发表我的评论
取消评论

*

表情