C++ :学习Proxy Class之笔记2

类别:编程语言 点击:0 评论:0 推荐:

依然是对more effective c++条款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 theArray.array[itemIndex];
  }


 private:
  Array& theArray;
  int itemIndex;
 };

 const Proxy operator[](int index) 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;
 friend ostream& operator<<(ostream& os, const Rational& rhs);


private:
 int num;
 int deno;
};

Rational::Rational(int numerator, int denominator)
: num(numerator), deno(denominator)
{
 std::cout << "Rational Construct" << std::endl;
}

int Rational::numerator() const
{
 std::cout << "numerator" << std::endl;
 return 0;
}

int Rational::denominator() const
{
 std::cout << "denominator" << std::endl;
 return 0;
}

ostream& operator<<(ostream& os, const Rational& rhs)
{
 os << rhs.num << " " << rhs.deno;
 return os;
}

int main()
{
 Array a(5);
 a[1].numerator();          //错误
}

之所以出现错误的原因是:operator[] 返回一个代理对象而不是实际的Rational对象。但成员函数numerator()和denominator()只存在于Rational对象上,而不是其代理对象。

但是我想,为什么编译器在这里不调用隐式转换函数

  operator T() const
  {
   return theArray.array[itemIndex];
  }

呢?如果调用了,那么错误也就应该不会出现了

一个简单的解决办法是

int main()
{
 Array a(5);
 (( Rational ) a[1] ).numerator();  
}

本文地址:http://com.8s8s.com/it/it28247.htm