zoukankan      html  css  js  c++  java
  • C++官方文档-运算符重载

    #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; }
  • 相关阅读:
    决策树
    结巴分词demo
    线性回归分析波士顿房价
    将python的字典格式数据写入excei表中
    ubuntu16.04电脑重启/关机卡死问题记录
    Hadoop 平台搭建
    Linux 常用命令
    灰度共生矩阵
    图像类型
    linux中的一些常用命令
  • 原文地址:https://www.cnblogs.com/shuiyonglewodezzzzz/p/8448438.html
Copyright © 2011-2022 走看看