0

私はこの問題を数日間理解しようとしてきましたが、以下のコードにすべてをストライピングした後、最終的にそれを理解しました。以下のコードでは、const_iteratorのコンストラクターでの3つの異なる試行と、そのうちの2つで発生するエラーを確認できます。コンパイラがローカルで宣言されたmine::iteratorの代わりにstd::iteratorを使用しようとしているように見えます。そうなのか?

手がかりを与えた他のちょっとしたこと:

  • mine ::iteratorにmine:: Bのような別の名前を付けると、const_iterator(const B &rhs)機能します。

  • std :: iterator以外のクラスからconst_iteratorを派生させると、const_iterator(const iterator<T> &rhs)機能します。

情報をありがとう。コードは次のとおりです。

#include "stdafx.h"
#include <iterator>

namespace mine 
{

   template <class T>
   class iterator : public std::iterator<std::random_access_iterator_tag, T, ptrdiff_t, T*, T&>
   {
   public:
      iterator() {}
   };   

   template <class T>
   class const_iterator : public std::iterator<std::random_access_iterator_tag, T, ptrdiff_t, const T*, const T&>
   {
   public:
      const_iterator() {} 
      const_iterator(const mine::iterator<T> &rhs) {} // works
      //const_iterator(const iterator &rhs)        {} // error C2440: initializing: cannot convert from 'mine::iterator<T>' to 'mine::const_iterator<T>'
      //const_iterator(const iterator<T> &rhs)     {} // error C2976: std::iterator: too few template arguments
   }; 

}// namespace mine

using namespace mine;

int _tmain(int argc, _TCHAR* argv[])
{
   iterator<int> y;
   const_iterator<int> x = y;

   return 0;
}
4

1 に答える 1

0

まず第一に' using namespace'は邪悪です、使いtypedefやすさのために使用してください。たとえば、イテレータと言う代わりに、mine::iteratorを使用します。

また、あなたの2番目のポイントはあなたの質問の答えを与えます。「std::iterator以外のクラスからconst_iteratorを派生させると、const_iterator(const iterator<T> &rhs)機能します。」

stdここで、最も近いイテレータはnotに属し、の基本クラスもmine同様です。std::iteratorconst_iterator

于 2012-10-20T11:06:36.227 に答える