. Buna ek olarak, tam bir örnek. I proxy_T
sınıfında, bir "kullanıcı tanımlı dönüşüm", diğer bir deyişle, operator T
ilave unutmayın.
#include <iostream>
#include <array>
#include <stdexcept>
template <class T>
class myClass
{
std::array<T, 5> TheArray; // Some array...
class proxy_T
{
T& value; // Reference to the element to be modified
public:
proxy_T(T& v) : value(v) {}
proxy_T& operator=(T const& i)
{
if (i >= 0 and i <= 9)
{
value = i;
}
else
{
throw std::range_error(std::to_string(i));
}
return *this;
}
operator T() // This is required for getting a T value from a proxy_T, which make the cout-lines work
{
return value;
}
};
public:
proxy_T operator [](int const idx)
{
return TheArray.at(idx);
}
T operator [](int const idx) const
{
return TheArray[idx];
}
};
int main() {
myClass<int> A;
std::cout << A[0] << std::endl;
A[0] = 2;
std::cout << A[0] << std::endl;
A[1] = 20;
}
Bunun yerine öğeyi saran bir proxy nesnesini döndürmeniz ve bunu atamada atamayı gerçekleştirmeniz gerekir. –
Kontrol ile ne demek istiyorsun? bir derleme hatası yangın istiyorsanız veya çalışma bir istisna istiyor musunuz, yoksa sessizce atama görmezden istiyorsun, yoksa kesme değerleri Menzile değilse istiyorsun musunuz? biz her zaman sınıfları hakkında ne gibi – taskinoor
@taskinoor ... Biz istisnalar atmak istiyorum! – geradism