.NODE

References to const

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

(1)Changes a temporary that's about to be destroyed.

(2)Error: Can't change const&.

(3)Changes the original Qstring.

(4)No temporaries are created.

(5)Error: Cannot convert to a QString&.

(6)char* converts to temporary and gets passed by const reference.

(7)Temporary QString #1 is created to convert char* to QString. Temporary #2 is created when it is passed by value.

(8)No temporaries are created.


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





An Introduction to Design Patterns in C++ with Qt 4
An Introduction to Design Patterns in C++ with Qt 4
ISBN: 0131879057
EAN: 2147483647
Year: 2004
Pages: 268
Similar book on Amazon

Flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net