菜菜

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
#include <iostream>
using namespace std;

class CVector
{
public:
    int x, y;
    CVector()
            : x(0), y(0)
    {
    }
    CVector(int a, int b)
            : x(a), y(b)
    {
    }
    ;
    CVector operator +(const CVector&);
};

//+号是双目运算,这个成员函数的形式
CVector CVector::operator +(const CVector& param)
{
    CVector temp;
    temp.x = x + param.x;
    temp.y = y + param.y;
    return temp;
}

//+号的非成员函数形式
CVector operator+(const CVector& lhs, const CVector& rhs)
{
    cout<<"no member function"<<endl;
    CVector temp;
    temp.x = lhs.x + rhs.x;
    temp.y = lhs.y + rhs.y;
    return temp;
}
/**
 *运算符重载表,注意成员函数和非成员函数的区别
 * Expression    Operator                                         Member function        Non-member function
 * @a            + - * & ! ~ ++ --                                A::operator@()         operator@(A)
 * a@            ++ --                                            A::operator@(int)      operator@(A,int)
 * a@b           + - * / % ^ & | < > == != <= >= << >> && || ,    A::operator@(B)        operator@(A,B)
 * a@b           = += -= *= /= %= ^= &= |= <<= >>= []             A::operator@(B)          -
 * a(b,c...)     ()                                               A::operator()(B,C...)    -
 * a->b          ->                                               A::operator->()          -
* (TYPE) a TYPE A::operator TYPE() -
*/ int main() { CVector foo(3, 1); CVector bar(1, 2); CVector result; CVector result2 = foo.operator +(bar); result = foo + bar; CVector result3 = foo+bar; cout << result.x << ',' << result.y << endl; cout << result2.x << ',' << result2.y << endl; cout << result3.x << ',' << result3.y << endl; return 0; }

 

posted on 2018-02-14 15:46  好吧,就是菜菜  阅读(149)  评论(0编辑  收藏  举报