5.9.  Overloading on const

[ fromfile: constoverloading.xml id: constoverloading ]

Example 5.16. src/const/overload/constoverload.h

#ifndef CONSTOVERLOAD_H
#define CONSTOVERLOAD_H
#include <iostream>
class Point3 {                                  1
 public:
    friend std::ostream& operator<<(std::ostream& out, const Point3& v);
    Point3(double x = 0, double y = 0, double z = 0);
    double& operator[](int index);    
    const double& operator[](int index) const;  2
    Point3 operator+(const Point3& v) const;
    Point3 operator-(const Point3& v) const;
    Point3 operator*(double s) const;           3
 private:
    static const int cm_Dim = 3;
    double m_Coord[cm_Dim];
};
#endif

1

3-dimension point (of double).

2

Overloaded on const-ness.

3

Scalar multiplication.


Example 5.17. src/const/overload/constoverload.cpp

[ . . . . ]
const double& Point3::operator[](int index) const {
    if ((index >= 0) && (index < cm_Dim))
        return m_Coord[index];
    else
        return zero(index);
}

double& Point3::operator[](int index) {
    if ((index >= 0) && (index < cm_Dim))
        return m_Coord[index];
    else
        return zero(index);
 }
 
[ . . . . ]