C ++: Learn the notebook notes for Proxy Class 2

xiaoxiao2021-03-06  74

It is still a study notes for more effective C Terms 30-Proxy Class.

#include

Using namespace std;

Template

Class Array

{

PUBLIC:

Class Proxy

{

PUBLIC:

Proxy (Array & Array, Int Index)

: THEARRAY (Array), ItemIndex (INDEX)

{}

Proxy & operator = (const t & rhs) {THEARRAY.Array [itemindex] = rhs; return * this;} Operator t () const {return thealay.Array [itemIndex];

Friend Ostream & Operator << (Ostream & OS, Const Proxy & RHS) {OS << RHS.THEARRAY [RHS.ITEMINDEX]; RETURN OS;

Private: Array & THEARRAY; INT ITEMINDEX;

Const proxy operator [] "const; proxy operator [] (int index);

Friend Class Proxy; Array (int Dim); ~ array ();

PRIVATE: T * array;

Template

Array

:: Array (int Dim)

{

Array = New T [DIM];

}

Template

Array

:: ~ array ()

{

delete [] array;

}

Template

Array

:: Proxy Array

:: Operator [] (int INDEX)

{

Return Proxy (* this, index);

}

Template

Const array

:: Proxy Array

:: Operator [] (int index) Const

{

Return Proxy (const_cast (* this), index;

}

class Rational {public: Rational (int numerator = 0, int denominator = 1); int numerator () const; int denominator () const; Rational & operator = (const Rational & rhs); friend ostream & operator << (ostream & os, const Rational & RHS);

PUBLIC: INT NUM; INT DENO;

Rational :: Rational (int name): Num (namerator), DENO (Denominator) {std :: cout << "Rational Construct << std :: endl;}

int Rational :: Numerator () const {std :: cout << "numerator:" << Num <

Return 0;

}

INT Rational :: Denominator () const {std :: cout << "Denominator:" << DENO << std :: endl; return 0;}

Rational & Rational :: Operator = (Const Rational & RHS) {Num = rhs.Num; DENO = rhs.deno; return * this;}

Ostream & Operator << (Ostream & OS, Const Rational & Rhs) {OS << rhs.num << "<< rhs.deno; return os;

Int main () {Array

a (5);

a [1] .Numerator (); //

error}

The reason why the error occurring is: Operator [] Returns a proxy object rather than the actual Rational object. But the member function Numerator () and Denominator () are only on the Rational object, not their agent objects.

But I think, why do the compiler not call an implicit conversion function here?

Operator t () const {return thearray.Array [itemindex];

? If the call is called, then the error should not appear.

A simple solution is

Int main () {Array

a (5);

(Rational) a [1]) .Numerator ();

}

转载请注明原文地址:https://www.9cbs.com/read-121144.html

New Post(0)