C++ 重载运算符

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++ 允许在同一作用域中的某个函数和运算符指定多个定义,分别称为函数重载和运算符重载。 重载声明是指一个与之前已...
    资深小夏阅读 492评论 0 0
  • 运算符 C++ 预定义表示对数据的运算只能用于基本的数据类型 C++ 提供了数据抽象的手段用户自己定义数据类型 -...
    Mitchell阅读 526评论 0 0
  • C++运算符重载-上篇 本章内容:1. 运算符重载的概述2. 重载算术运算符3. 重载按位运算符和二元逻辑运算符4...
    Haley_2013阅读 2,323评论 0 51
  • C++运算符重载-下篇 本章内容:1. 运算符重载的概述2. 重载算术运算符3. 重载按位运算符和二元逻辑运算符4...
    Haley_2013阅读 1,478评论 0 49
  • 注意:本文中代码均使用 Qt 开发编译环境 面向对象的多态性可以分为四类:重载多态、强制多态、包含多态和参数多态,...
    赵者也阅读 1,177评论 0 3