Skip to content

Comment on Write a program that makes 2 + 2 = 5

Comments

why not just overload the + operator in C++?

first thing i thought when i read the title:

    #include <iostream>

    class Int
    {
    private:
            int _value;

    public:
	    Int(int value) : _value(value) {}
	    Int operator + (const Int& b){ return Int(++_value + b._value); }
	    friend std::ostream& operator << (std::ostream& out, const Int& value){ out << value._value; return out; }
    };

    int main(int argc, char** argv)
    {
	    std::cout << Int(2) + Int(2) << std::endl;
            return 0;
    }
output: 5
AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.