C++ question about overloading a type cast

Discussion in 'OT Technology' started by zanyspy_dude, Apr 8, 2008.

  1. zanyspy_dude

    zanyspy_dude King of teh n00bz

    Joined:
    Aug 29, 2002
    Messages:
    4,473
    Likes Received:
    0
    Location:
    Indianapolis, IN
    I want to define a cast from my class to double...it would look like this

    RatNum a;

    Code:
    cout << (double) a << endl;
    How do i define this? So far I can't find anything that works...Thanks


    I'm using visual studio and am beginning to think this is the problem.
     
    Last edited: Apr 8, 2008
  2. TheDarkHorizon

    TheDarkHorizon \xC0\xFF\xEE

    Joined:
    Sep 26, 2002
    Messages:
    2,396
    Likes Received:
    0
    Location:
    San Francisco, CA
    operator double() {}

    Example:

    Code:
    #include <iostream>
    
    using namespace std;
    
    class RatNum {
    private:
        double num;
    
    public:
        RatNum(double n) : num(n) {}
    
        operator double() {
            return this->num;
        }   
    };
    
    int main(int argc, char **argv) {
        RatNum r(3.14);
    
        cout << (double) r << endl;
    
        return 0;
    }
    
     
  3. Coottie

    Coottie BOOMER......SOONER OT Supporter

    Joined:
    Jun 6, 2006
    Messages:
    32,407
    Likes Received:
    0
    Location:
    OKC
    need more info....define your class.

    Also, use the code tags. You're an :02: you should know this. ;)
    edit: damn...i'm too slow
     
  4. zanyspy_dude

    zanyspy_dude King of teh n00bz

    Joined:
    Aug 29, 2002
    Messages:
    4,473
    Likes Received:
    0
    Location:
    Indianapolis, IN
    here is my .hpp file.

    Code:
    #include <iostream>
    #include <sstream>
    #include <cmath>
    #include <string>
    
    class RatNum
    {
    private:
    	int num;
    	int den;
    public:
    	RatNum(void);
    	RatNum(int numerator, int denominator);
    	~RatNum(void);
    	bool operator+(RatNum RHS);
    	bool operator-(RatNum RHS);
    	bool operator*(RatNum RHS);
    	bool operator/(RatNum RHS);
    	bool operator!();
    	bool operator<(RatNum RHS);
    	bool operator==(RatNum RHS);
    	operator(double)();
    	friend std::istream& operator>>(std::istream& ins, RatNum& fraction);
    	friend std::ostream& operator<<(std::ostream&outs, const RatNum& fraction);
    };
    
    I'm not sure how to make that match with what is above.
     
  5. TheDarkHorizon

    TheDarkHorizon \xC0\xFF\xEE

    Joined:
    Sep 26, 2002
    Messages:
    2,396
    Likes Received:
    0
    Location:
    San Francisco, CA
    Code:
    RatNum::operator double() {
      return (double)this.num / (double)this.den;
    }
    
     
  6. zanyspy_dude

    zanyspy_dude King of teh n00bz

    Joined:
    Aug 29, 2002
    Messages:
    4,473
    Likes Received:
    0
    Location:
    Indianapolis, IN
    Thank you so much for your help!!!
     

Share This Page