Define a primitive data type: Difference between revisions
Content added Content deleted
No edit summary |
(C++ version) |
||
Line 10: | Line 10: | ||
B : My_Type := A; |
B : My_Type := A; |
||
The compiler will omit bounds checking for the assignment of A to B above because both values are of My_Type. A cannot hold a value outside the range of 1..10, therefore the assignment cannot produce an out of bounds result. |
The compiler will omit bounds checking for the assignment of A to B above because both values are of My_Type. A cannot hold a value outside the range of 1..10, therefore the assignment cannot produce an out of bounds result. |
||
==[[C plus plus|C++]]== |
|||
[[Category:C plus plus]] |
|||
'''Compiler:''' [[GCC]] |
|||
This class relies on implicit conversions to do most int operations; however the combined operations with assignment have to be coded explicitly. |
|||
#include <stdexcept> |
|||
class tiny_int |
|||
{ |
|||
public: |
|||
tiny_int(int i): |
|||
value(i) |
|||
{ |
|||
if (value < 1) |
|||
throw std::out_of_range("tiny_int: value smaller than 1"); |
|||
if (value > 10) |
|||
throw std::out_of_range("tiny_int: value larger than 10"); |
|||
} |
|||
operator int() const |
|||
{ |
|||
return value; |
|||
} |
|||
tiny_int& operator+=(int i) |
|||
{ |
|||
// by assigning to *this instead of directly modifying value, the |
|||
// constructor is called and thus the check is enforced |
|||
*this = value + i; |
|||
return *this; |
|||
} |
|||
tiny_int& operator-=(int i) |
|||
{ |
|||
*this = value - i; |
|||
return *this; |
|||
} |
|||
tiny_int& operator*=(int i) |
|||
{ |
|||
*this = value * i; |
|||
return *this; |
|||
} |
|||
tiny_int& operator/=(int i) |
|||
{ |
|||
*this = value / i; |
|||
return *this; |
|||
} |
|||
tiny_int& operator<<=(int i) |
|||
{ |
|||
*this = value << i; |
|||
return *this; |
|||
} |
|||
tiny_int& operator>>=(int i) |
|||
{ |
|||
*this = value >> i; |
|||
return *this; |
|||
} |
|||
tiny_int& operator&=(int i) |
|||
{ |
|||
*this = value & i; |
|||
return *this; |
|||
} |
|||
tiny_int& operator|=(int i) |
|||
{ |
|||
*this = value | i; |
|||
return *this; |
|||
} |
|||
private: |
|||
unsigned char value; // we don't need more space |
|||
}; |
|||
==[[Perl]]== |
==[[Perl]]== |