C++ Tutorial/Operator Overloading/enum operator — различия между версиями


Deprecated: Constant E_STRICT is deprecated in /var/www/cppe.ru/www/includes/exception/MWExceptionHandler.php on line 179

Deprecated: Creation of dynamic property PPDStack::$accum is deprecated in /var/www/cppe.ru/www/includes/parser/Preprocessor_DOM.php on line 803

Deprecated: Constant E_STRICT is deprecated in /var/www/cppe.ru/www/includes/exception/MWExceptionHandler.php on line 179

Deprecated: Constant E_STRICT is deprecated in /var/www/cppe.ru/www/vendor/mediawiki/at-ease/src/Functions.php on line 48
Материал из C\C++ эксперт
Перейти к: навигация, поиск
м (1 версия: Импорт контента...)
 
м (1 версия: Импорт контента...)
 
(нет различий)

Текущая версия на 10:30, 25 мая 2010

Overloading operators for enumerations

#include <string>
#include <iostream>
#include <ostream>
#include <cstdlib>
enum Week { Monday=0, Tuesday=1, Wednesday=2, Friday=4 };
// Explicitly cast to int, to avoid infinite recursion.
inline Week operator|(Week a, Week b) {
  return Week(int(a) | int(b));
}
inline Week& operator|=(Week& a, Week b) {
  a = a | b;
  return a;
}
inline Week operator&(Week a, Week b) {
  return Week(int(a) & int(b));
}
inline Week& operator&=(Week& a, Week b) {
  a = a & b;
  return a;
}
inline Week operator^(Week a, Week b) {
  return Week(int(a) ^ int(b));
}
inline Week& operator^=(Week& a, Week b) {
  a = a ^ b;
  return a;
}
inline Week operator~(Week a) {
  return Week(~int(a));
}
bool error()
{
  return std::rand()  2 != 0;
}
int main()
{
  Week a = Monday;
  std::cout << a << std::endl;
  a |= Tuesday;
  std::cout << a;
}
0
1