About overloading operators.

This is a discussion on About overloading operators. within the C++ Programming forums, part of the General Programming Boards category; Can you 'create' new operators? Like a +++ which would, for example add two to the variable? I tried making ...

  1. #1
    Registered User Dual-Catfish's Avatar
    Join Date
    Sep 2001
    Posts
    802

    About overloading operators.

    Can you 'create' new operators? Like a +++ which would, for example add two to the variable? I tried making a simple program to find the answer for myself. But I failed miserably; I don't know if it's because I'm overlooking something, or you simply cannot do what I'm asking.

    Code:
    #include <iostream.h>
    typedef unsigned short int USHORT;
    
    class addthis
    {
    public:
    	addthis() { val = 0; } 
    	~addthis() {}
    	addthis(USHORT x) { setVal(x); }
    	USHORT getVal() { return val; }
    	void setVal(USHORT x) { val = x; }
    	addthis operator+++ ();
    	addthis operator++ ();
    private:
    	USHORT val;
    }
    
    addthis addthis::operator+++()
    {
    	val = val+2;
    }
    
    addthis addthis::operator++()
    {
    	val = ++val;
    }
    
    int main(void)
    {
    	addthis ADDTHIS(22);
    	cout << ADDTHIS.getVal();
    	ADDTHIS+++;
    	cout << ADDTHIS.getVal();
    	ADDTHIS++;
    	cout << ADDTHIS.getVal();
    	ADDTHIS.flush();
    	cout << "ADDTHIS.getVal();
    	SYSTEM("PAUSE");
    	return 0;
    }
    I got numerous errors in this code. I'm not asking for it to be debugged, I would just like to know if I'm implementing the overload of operators properly.

  2. #2
    zen
    zen is offline
    of Zen Hall zen's Avatar
    Join Date
    Aug 2001
    Posts
    1,007
    No you can't, you are restricted to the existing ones minus a few.
    zen

  3. #3
    Registered User
    Join Date
    Dec 2001
    Posts
    194
    Using the += would be better than your desired +++ operator

    object +=2; would add 2 to the object, so simply overload the += operator

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. question about overloading operators
    By *DEAD* in forum C++ Programming
    Replies: 9
    Last Post: 05-08-2008, 10:27 AM
  2. Replies: 16
    Last Post: 10-27-2007, 12:42 PM
  3. Overloading fstream's << and >> operators
    By VirtualAce in forum C++ Programming
    Replies: 2
    Last Post: 04-09-2007, 03:17 AM
  4. operators overloading
    By waqasriazpk in forum C++ Programming
    Replies: 1
    Last Post: 07-26-2002, 01:05 AM
  5. Overloading operators...
    By Unregistered in forum C++ Programming
    Replies: 4
    Last Post: 11-21-2001, 07:24 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21