Overload int() Operator, assign an object to a built-in value - C++ Class

C++ examples for Class:Operator Overload

Description

Overload int() Operator, assign an object to a built-in value

Demo Code

                                                        
#include <iostream> 
                                                           
class Counter //from ww w.  ja v  a  2s . c o m
{ 
public: 
    Counter(); 
    ~Counter() {} 
    Counter(int newValue); 
    int getValue() const { return value; } 
    void setValue(int newValue) { value = newValue; } 
    operator unsigned int(); 
private: 
    int value; 
}; 
                                                           
Counter::Counter(): 
value(0) 
{} 
                                                         
Counter::Counter(int newValue): 
value(newValue) 
{} 
                                                         
Counter::operator unsigned int() 
{ 
    return (value); 
} 
                                                           
int main() 
{ 
    Counter epsilon(19); 
    int zeta = epsilon; 
    std::cout << "zeta: " << zeta << std::endl; 
    return 0; 
}

Result


Related Tutorials