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;
}