美文网首页
C++ 重载运算符

C++ 重载运算符

作者: DayDayUpppppp | 来源:发表于2017-04-26 18:38 被阅读0次

C++重载运算符

class Point3d {
private:
    float _x;
    float _y;
    float _z;
public:
    Point3d(float x=0.0,float y=0.0,float z=0.0):_x(x),_y(y),_z(z){}

    //重载<<
    friend ostream& operator<<(ostream &os, const Point3d &pt) {
        return os << pt._x << " , " << pt._y << " , " << pt._z << endl;
    }

    //重载>>
    friend istream& operator>>(istream &is,Point3d &pt) {
        is >> pt._x >> pt._y >> pt._z;
        return is;
    }

    //重载[]
    float operator[](int index) {
        if (index < 0 || index>2) {
            cout << "error" << endl;
        }
        else {
            if (index == 0) {return _x;}
            if (index == 1) {return _y;}
            if (index == 2) { return _z; }
        }
    }
};

int main() {
    Point3d p;
    cout << p << endl;;
    cin >> p;
    cout << p << endl;;
    cout << p[0] << endl;
}

相关文章

  • 第十一章 使用类

    运算符重载 运算符重载是一种形式的C++多态。运算符重载将重载的概念扩展到运算符上,允许赋予C++运算符多种含义。...

  • 1.2.15_C++ 关系运算符重载

    C++ 重载运算符和重载函数 C++ 语言支持各种关系运算符( < 、 > 、 <= 、 >= 、 == 等等),...

  • C++ 运算符重载

    运算符重载将重载的概念扩展到运算符上,允许赋予C++运算符多种含义。实际上,很多C++运算符已经重载。将*运算符用...

  • C++运算符重载

    C++运算符重载的实质:运算符重载的实质就是函数重载或函数多态。运算符重载是一种形式的C++多态。目的在于让人能够...

  • C++运算符重载-下篇 (Boolan)

    C++运算符重载-下篇 (Boolan) 本章内容:1. 运算符重载的概述2. 重载算术运算符3. 重载按位运算符...

  • C++运算符重载-上篇 (Boolan)

    C++运算符重载-上篇 (Boolan) 本章内容:1. 运算符重载的概述2. 重载算术运算符3. 重载按位运算符...

  • C++ 重载运算符

    C++重载运算符

  • C++重载

    重载 C++语言规定: 重载的运算符要保持原运算符的意义。只能对已有的运算符重载,不能增加新的运算符。重载的运算符...

  • 1.2.17_C++ ++ 和 -- 运算符重载

    C++ 重载运算符和重载函数 递增运算符( ++ )和递减运算符( -- )是 C++ 语言中两个重要的一元运算符...

  • C++运算符重载详解

    运算符重载规则 1.被重载的运算符必须是已经存在的C++运算符,不能重载自己创建的运算符; 2.运算符被重载之后,...

网友评论

      本文标题:C++ 重载运算符

      本文链接:https://www.haomeiwen.com/subject/lylwzttx.html