Declaring a reference parameter to be const tells the compiler to make sure that the function does not attempt to change that object. For objects larger than a pointer, a reference to const is an efficient alternative to a value parameter because no data is copied. Example 5.14 contains three functions, each accepting a parameter in a different way.
Example 5.14. src/const/reference/constref.cpp
class Person { public: void setNameV( QString newName) { newName += " Smith"; <-- 1 m_Name = newName; } void setNameCR( const QString& newName) { // newName += " Python"; <-- 2 m_Name = newName; } void setNameR( QString& newName) { m_Name += " Dobbs"; <-- 3 m_Name = newName; } private: QString m_Name; }; int main() { Person p; QString name("Bob"); p.setNameCR(name); <-- 4 // p.setNameR("Monty"); <-- 5 p.setNameCR("Monty"); <-- 6 p.setNameV("Connie"); <-- 7 p.setNameR(name); <-- 8 cout << name; }
|
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