Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Overloading operators

Name: Anonymous 2006-06-09 23:57

What does this mean in english (refering to C++)

Name: Anonymous 2006-06-10 3:28

>>2
Well I know how to do it in C++ if that's cool:
#include <iostream>

// In this implementation the numbers will not scale, for simplicity of the example
// and because it's fucking late here.
template <typename T>
class Number {
      T *m_value;
public:
      const T &value; // a reference to internal data      
      Number (T val_in = 0) : m_value(new T(val_in)), value(*m_value) {  }
      ~Number() { delete m_value; }
     
      Number operator+ (const Number &rhs) {
             return Number(value + rhs.value);
      }
     
      // asignment operator for Numbers
      Number &operator= (const Number &rhs) {
             if (this == &rhs)
             // if this is true, we attempted to assign an object to itself.
                return *this;
             delete m_value; // but if it isn't the same object, delete the old data
             m_value = new T(rhs.value); // and replace it with new data
             return *this; 
      }   
};

int main() {
    Number<double> a = 2.2e6, b = 4.2933e3;
    Number<double> c = b + a;
    std::cout << a.value << " " << b.value << " " << c.value;
    return 0;
}

Name: Anonymous 2006-06-14 12:29

This is >>6. I'm not sure what you meant or tried to do to my program but it won't add Number<int>s to Number<double>s or anything like that -- like I told you in the comment: Numbers will not scale. The templates would need some work in order to do that, and I wrote that at 3:30 am.

My destructor is fine. I didn't declare any array space on the heap so delete[] has no reason to be there.

The output works as it should.

Name: Anonymous 2006-06-14 17:32

>>6,10,11 Nevermind my idiocy... I should have just wrote this better, period. Here's something:
#include <iostream>

template <typename T> class Number {
    T *m_value;
public:
    Number(T val_in = 0) : m_value(new T(val_in)) {  }
    ~Number() { delete m_value; }
   
    Number operator+ (const Number &rhs) {
        return Number(*m_value + *(rhs.m_value));
    }
    Number &operator= (const Number &rhs) {
        if (this == &rhs)
            return *this;
        delete m_value;
        m_value = new T(*(rhs.m_value));
        return *this;
    }

    friend std::ostream &operator<< (std::ostream& outs, const Number &n) {
        return outs << *(n.m_value);
    }

};


int main() {
    Number<double> a = 5.453, b = 3.51, c;
    c = a + b;
    std::cout << a << " + " << b << " = " << c << "\n";
}

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List