C++ Tutorial/Operator Overloading/overload conversion 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++ эксперт
Перейти к: навигация, поиск

Conversion operator

#include <iostream>
 
 class MyType
 {
 public:
     MyType();
     MyType(int val);
     ~MyType(){}
     int getValue()const { return myValue; }
     void setValue(int x) {myValue = x; }
     operator unsigned short();
 private:
     int myValue;
 };
 
 MyType::MyType():myValue(0) {}
 
 MyType::MyType(int val): myValue(val) {}
 
 MyType::operator unsigned short ()
 {
     return ( int (myValue) );
 }
 
 int main()
 {
     MyType ctr(5);
     int theShort = ctr;
     std::cout << "theShort: " << theShort << std::endl;
     return 0;
 }
theShort: 5