operator overloading (prefix ++)
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3

Thread: operator overloading (prefix ++)

  1. #1
    Join Date
    Feb 2014
    Posts
    11

    operator overloading (prefix ++)

    Hi...

    I am writing the overloading operator function (prefix ++) according to my book.. but it doesnt work !!!!!!

    But if i write:
    void operator++()
    {
    ++x;
    }
    it works !!!!!
    Is the book wrong???

    Here is my code according to the book that doesnt work as it should:

    #include <iostream>
    using namespace std;

    class things
    {
    int x,y,z;

    public:
    void print()
    {

    cout<<x<<endl;
    cout<<y<<endl;
    cout<<z<<endl;
    cout<<"*****"<<endl;

    }
    things():x(0),y(0),z(0){};

    thing& operator ++() //******** here *******
    {
    ++x;
    return *this;
    }


    };

    int main()
    {

    things table;

    cout<<"*****"<<endl;

    table.print();

    ++table;

    table.print();

    return 0;
    }

  2. #2
    Join Date
    Aug 2000
    Location
    West Virginia
    Posts
    7,569

    Re: operator overloading (prefix ++)

    You have:

    Code:
    thing & operator ++() //******** here *******

    It should be things &

    Also, the problem with the void method is that you can not use operator ++
    in many ways that you would expect to .. Example:

    Code:
    things table2 = ++table;
    Last edited by Philip Nicoletti; February 4th, 2014 at 06:59 PM.

  3. #3
    Join Date
    Dec 2012
    Location
    England
    Posts
    2,458

    Re: operator overloading (prefix ++)

    Please format your code properly before posting and use code tags (Go advanced, select the code and click '#'). You code as posted is not very readable.

    When overloading the operator ++, there are two situations that need to be considered - pre and post increment.
    Prefix increment is defined as
    Code:
    things& operator++();
    whereas postfix increment is defined as
    Code:
    things operator++(int);
    See
    http://msdn.microsoft.com/en-us/library/f6s9k9ta.aspx
    All advice is offered in good faith only. You are ultimately responsible for effects of your programs and the integrity of the machines they run on.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center