Kombinowałem, jak zrobić własnego inta, który by zawsze wymuszał, że ma być w odpowiednim zakresie (np. od 0 do 100).
Oto, jak się do tego zabrałem:
#include <cassert>
#include <cstdint>
#include <iostream>
using namespace std;
int main();
class ConstrainedInt
{
public:
typedef uint_least8_t valtype;
private:
valtype val;
static const valtype minval = 0;
static const valtype maxval = 100;
static bool checkval (valtype val);
public:
ConstrainedInt();
ConstrainedInt(valtype);
ConstrainedInt &operator = (valtype);
operator const valtype&();
};
bool ConstrainedInt::checkval (ConstrainedInt::valtype val)
{
return minval <= val && val <= maxval;
}
ConstrainedInt::ConstrainedInt() : val{0}
{
assert(checkval(val));
}
ConstrainedInt::ConstrainedInt (ConstrainedInt::valtype val) : val{val}
{
assert(checkval(val));
}
ConstrainedInt &ConstrainedInt::operator = (ConstrainedInt::valtype val)
{
assert(checkval(val));
this->val = val;
return *this;
}
ConstrainedInt::operator const ConstrainedInt::valtype&()
{
return *this;
}
int main()
{
ConstrainedInt i = 15;
cout << i;
return 0;
}
Dostaję Segmentation fault.
Dlaczego?