Thread: Operator Overloading

  1. #1
    Registered User
    Join Date
    Sep 2005
    Posts
    57

    Operator Overloading

    K well we have an assiment to do the operator overloading and here is where i am stuck so for exmple we need to do in main program
    Code:
    ClassName n1;//Declaring variable
    int x;
    x=n1++;
    x=++n1;
    This is what i have in the calss but how do i tell diffirence between before and after. Thanks i hope u see what i mean.

    Code:
                               void operator ++()
    	   		  {
    			   	   ++number;
    	   		  }
    	   		  void operator ++()
    	   		  {
    			   	   number++
    	   		  }

  2. #2
    semi-colon generator ChaosEngine's Avatar
    Join Date
    Sep 2005
    Location
    Chch, NZ
    Posts
    597
    ahh this is a tricksy one! in order to tell the difference, the committee added an int parameter to the postfix operator. It's a bit of a hack, but it works.

    Code:
    class X
    {
    public:
        X operator++(int); // postfix operator (i.e. x++)
        X& opertor++(); // prefix operator (i.e. ++x)
    };
    note that the postfix returns an object and the prefix returns a reference. This is because postfix makes a copy BEFORE the increment and returns that. prefix just returns *this.

    This is why you should always use prefix unless you have a good reason not to.

    edit: BTW the extra parameter must be an int. you don't use the value anyway.
    "I saw a sign that said 'Drink Canada Dry', so I started"
    -- Brendan Behan

    Free Compiler: Visual C++ 2005 Express
    If you program in C++, you need Boost. You should also know how to use the Standard Library (STL). Want to make games? After reading this, I don't like WxWidgets anymore. Want to add some scripting to your App?

  3. #3
    Registered User
    Join Date
    Sep 2005
    Posts
    57
    Yah thanks that worked that was simple assiment phew lol last one we did was double link list and swap function gar hate that one but beside that thanks.

Popular pages Recent additions subscribe to a feed