[ fromfile: constoverloading.xml id: constoverloading ]
const
changes the signature of a member function.
This means that functions can be overloaded on const
-ness.
Example 5.16. src/const/overload/constoverload.h
#ifndef CONSTOVERLOAD_H #define CONSTOVERLOAD_H #include <iostream> class Point3 { 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; Point3 operator+(const Point3& v) const; Point3 operator-(const Point3& v) const; Point3 operator*(double s) const; private: static const int cm_Dim = 3; double m_Coord[cm_Dim]; }; #endif
The operator function definitions are shown in Example 5.17.
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); } [ . . . . ]
If index
is in range, each function returns m_Coord[index]
- so what is the difference between them?
Generated: 2012-03-02 | © 2012 Alan Ezust and Paul Ezust. |