h1970
Senior Member
Em có ca này nhờ các cao nhân C++ trợ giúp. Đây là đoạn code mà em đang loay hoay mãi chưa hiểu tạo sao bị lỗi
Code này em có 2 classes. Một là IntArray là container cho mảng int, tính năng nó kiểu như vector rút gọn. Class còn lại là IntArrayIterator dùng để duyệt cái IntArray. Khi compile thì gặp lỗi ở dòng này
return fContainer[fPosition];
báo là no match for 'operator[]' (operand types are 'const IntArray' and 'const size_t' {aka 'const long long unsigned int'})
trong khi ở class IntArray em đã có cái operator[] ở đây rồi
const int IntArray:perator[](size_t aIndex) const
{
return fElements[aIndex];
}
Cảm ơn các bác.
C++:
#include <cstddef>
#include <iostream>
class IntArray;
class IntArrayIterator
{
private:
const IntArray& fContainer;
size_t fPosition;
public:
IntArrayIterator(const IntArray& aContainer, size_t aStart = 0);
const int operator*() const;
IntArrayIterator& operator++(); // prefix
bool operator==(const IntArrayIterator& aRHS) const;
bool operator!=(const IntArrayIterator& aRHS) const;
IntArrayIterator begin() const;
IntArrayIterator end() const;
};
IntArrayIterator::IntArrayIterator(const IntArray& aContainer, size_t aStart): fContainer(aContainer), fPosition(aStart){}
const int IntArrayIterator::operator*() const
{
return fContainer[fPosition];
}
IntArrayIterator& IntArrayIterator::operator++()
{
fPosition++;
return *this;
}
bool IntArrayIterator::operator==(const IntArrayIterator& aRHS) const
{
return fPosition == aRHS.fPosition;
}
bool IntArrayIterator::operator!=(const IntArrayIterator& aRHS) const
{
return !(*this == aRHS);
}
class IntArray
{
private:
const int* fElements;
size_t fNumberOfElements;
public:
IntArray(const int aArrayOfIntegers[], size_t aNumberOfElements);
const int operator[](size_t aIndex) const;
IntArrayIterator begin() const;
IntArrayIterator end() const;
};
IntArray::IntArray(const int aArrayOfIntegers[], size_t aNumberOfElements) : fElements(aArrayOfIntegers), fNumberOfElements(aNumberOfElements){}
const int IntArray::operator[](size_t aIndex) const
{
return fElements[aIndex];
}
IntArrayIterator IntArray::begin() const
{
return IntArrayIterator(*this, 0);
}
IntArrayIterator IntArray::end() const
{
return IntArrayIterator(*this, fNumberOfElements);
}
int main()
{
int a[] = {5,10,15};
IntArray iv(a, 3);
for (const auto& it:iv)
{
std::cout << it << std::endl;
}
return 0;
}
Code này em có 2 classes. Một là IntArray là container cho mảng int, tính năng nó kiểu như vector rút gọn. Class còn lại là IntArrayIterator dùng để duyệt cái IntArray. Khi compile thì gặp lỗi ở dòng này
return fContainer[fPosition];
báo là no match for 'operator[]' (operand types are 'const IntArray' and 'const size_t' {aka 'const long long unsigned int'})
trong khi ở class IntArray em đã có cái operator[] ở đây rồi
const int IntArray:perator[](size_t aIndex) const
{
return fElements[aIndex];
}
Cảm ơn các bác.