.NODE

Friends of a Class

Now that we know about accessibility rules, we need to know how to break them occasionally. The friend mechanism makes it possible for a class to allow non-member functions to access its private data. The keyword friend is followed by a class or a function declaration. friend declarations are located inside a class definition. Here are some syntax examples.

class Timer {
 friend class Clock;
 friend void Time::toString();
 friend ostream& operator <<(ostream& os, const Timer& obj);
 [ . . . ]

 private:
 long m_Elapsed;
};

A friend can be a class, a member function of another class, or a non-member function. In the previous example, class Clock is a friend, so all of its member functions can access Timer::m_Elapsed.Time::toString() is a friend of Timer and is assumed (by the compiler) to be a valid member of class Time. The third friend is a non-member function, an overloaded insertion operator, which inserts its second argument into the output stream and returns a reference to the stream so that the operation can be chained.

Breaking encapsulation can compromise the maintainability of your programs, so you should use the friend mechanism sparingly and carefully. Typically, friend functions are used for two purposes.

  1. For factory methods when we want to enforce creational rules (see Section 16.1.4) on a class
  2. For global operator functions such as << and >> when we do not wish to make the operator a member function, or do not have write-access to the class definition


Constructors

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