const changes the signature of a member function. This means that functions can be overloaded on const-ness. Example 5.16 shows a homemade vector class with member functions overloaded in this way.
Example 5.16. src/const/overload/constoverload.h
#ifndef CONSTOVERLOAD_H #define CONSTOVERLOAD_H #include 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
|
Exercises: Overloading on const-ness
1. |
In Example 5.17, the compiler can tell the difference between calls to the const and to the non-const versions of operator[] based on the const-ness of the object. |
Example 5.17. src/const/overload/constoverload-client.cpp
#include "constoverload.h" #include int main( ) { using namespace std; Point3 pt1(1.2, 3.4, 5.6); const Point3 pt2(7.8, 9.1, 6.4); double d ; d = pt2[2]; <-- 1 cout << d << endl; d = pt1[0]; <-- 2 cout << d << endl; d = pt1[3]; <-- 3 cout << d << endl; pt1[2] = 8.7; <-- 4 cout << pt1 << endl; // pt2[2] = 'd'; cout << pt2 << endl; return 0; }
|
Example 5.18. 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); } [ . . . . ] |
Inline Functions |
Part I: Introduction to C++ and Qt 4
C++ Introduction
Classes
Introduction to Qt
Lists
Functions
Inheritance and Polymorphism
Part II: Higher-Level Programming
Libraries
Introduction to Design Patterns
QObject
Generics and Containers
Qt GUI Widgets
Concurrency
Validation and Regular Expressions
Parsing XML
Meta Objects, Properties, and Reflective Programming
More Design Patterns
Models and Views
Qt SQL Classes
Part III: C++ Language Reference
Types and Expressions
Scope and Storage Class
Statements and Control Structures
Memory Access
Chapter Summary
Inheritance in Detail
Miscellaneous Topics
Part IV: Programming Assignments
MP3 Jukebox Assignments
Part V: Appendices
MP3 Jukebox Assignments
Bibliography
MP3 Jukebox Assignments