2009-05-04 2 views
3

В C# У меня есть следующий класс и компилируется нормально:Реализация GetEnumerator в C++

class CustomItem { }

class CustomList : IList<CustomItem> 
{ 
    public CustomItem this[int index] 
    { 
     get { return null; } 
     set { throw new NotImplementedException(); } 
    } 
    public void CopyTo(CustomItem[] array, int arrayIndex) 
    { 
    } 

    public int Count { get { return 10; } } 
    public int IndexOf(CustomItem item) { throw new NotImplementedException(); } 
    public void Insert(int index, CustomItem item) { throw new NotImplementedException(); } 
    public void RemoveAt(int index) { throw new NotImplementedException(); } 
    public void Add(CustomItem item) { throw new NotImplementedException(); } 
    public void Clear() { throw new NotImplementedException(); } 
    public bool Contains(CustomItem item) { throw new NotImplementedException(); } 
    public bool IsReadOnly { get { return true; } } 
    public bool Remove(CustomItem item) { throw new NotImplementedException(); } 

    public IEnumerator<CustomItem> GetEnumerator() { throw new NotImplementedException(); } 
    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() 
    { throw new NotImplementedException(); } 
} 

Когда я попробовать то же самое в C++ я получаю несколько ошибок компилятора:

ref class CustomItemValue { };

typedef CustomItemValue^ CustomItem; 

ref class CustomList : public IList<CustomItem> 
{ 
public: 
    property CustomItem default[int] 
    { 
     virtual CustomItem get(int index) { return nullptr; } 
     virtual void set(int index, CustomItem value) {} 
    } 
    virtual void CopyTo(array<CustomItem>^ array, int arrayIndex) 
    { 
    } 

    property int Count { virtual int get() { return 10; } } 
    virtual int IndexOf(CustomItem item) { throw gcnew NotImplementedException(); } 
    virtual void Insert(int index, CustomItem item) { throw gcnew NotImplementedException(); } 
    virtual void RemoveAt(int index) { throw gcnew NotImplementedException(); } 
    virtual void Add(CustomItem item) { throw gcnew NotImplementedException(); } 
    virtual void Clear() { throw new NotImplementedException(); } 
    virtual bool Contains(CustomItem item) { throw gcnew NotImplementedException(); } 
    property bool IsReadOnly { virtual bool get() { return true; } } 
    virtual bool Remove(CustomItem item) { throw gcnew NotImplementedException(); } 

    virtual IEnumerator<CustomItem>^ GetEnumerator() { throw gcnew NotImplementedException(); } 
    virtual System::Collections::IEnumerator^ GetEnumerator() 
    { throw gcnew NotImplementedException(); } 
}; 

Сообщения об ошибках компилятора:

.\mc.cpp(38) : error C2556: 'System::Collections::IEnumerator ^CustomList::GetEnumerator(void)' : overloaded function differs only by return type from 'System::Collections::Generic::IEnumerator ^CustomList::GetEnumerator(void)' with [ T=CustomItem ] .\mc.cpp(36) : see declaration of 'CustomList::GetEnumerator' .\mc.cpp(38) : error C2371: 'CustomList::GetEnumerator' : redefinition; different basic types .\mc.cpp(36) : see declaration of 'CustomList::GetEnumerator'

Может ли кто-нибудь помочь мне с этим?

+0

Интересно, не могли бы вы просто наследовать от Collection и просто использовать переопределения для определенных методов, которые хотите изменить? –

+0

Извините, но я не нашел класс Collection в .NET. Насколько я знаю, список или Array существует, но это не совсем то, что я хочу. Спасибо за ваше предложение, но мне нужно это, чтобы получить доступ к существующей реализации списка в .NET. Список реализован на C++, и я хочу получить к нему доступ. –

ответ

4

Вы должны использовать конкретный явный синтаксис переопределения Microsoft для переопределить как GetEnumerator() методы:

virtual System::Collections::IEnumerator^ GetEnumerator2() = System::Collections::IEnumerable::GetEnumerator 
{ throw gcnew NotImplementedException(); } 

virtual IEnumerator<CustomItem>^ GetEnumerator() 
{ throw gcnew NotImplementedException(); } 

Обратите внимание, что я переименовал, не универсальный метод GetEnumerator к GetEnumerator2 затем указывает, что он отменяет систему :: Коллекции :: IEnumerable :: GetEnumerator. Вы можете узнать больше о явном переопределении в here

+0

Спасибо, это именно то, что я искал. –

0

У вас есть ключ к сообщению об ошибке. ваш метод GetEnumerator возвращает System :: Collections :: IEnumerator ^, хотя есть еще один метод для этого класса, который возвращает System :: Collections :: Generic :: IEnumerator ^, этот метод, вероятно, унаследован от класса IList.

Попробуйте заменить возвращаемое значение системой :: Collections :: Generic :: IEnumerator ^.

+0

Извините, но я уже пробовал. Проблема заключается в том, что компилятор жалуется на второе определение GetEnumerator, но без него компилятор жалуется на недостающее определение функции (поскольку GetEnumerator является абстрактным). –

Смежные вопросы