Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
425 views
in Technique[技术] by (71.8m points)

c++ - Overload ++ operator

I am trying to deal with operator overloading at the first time, and I wrote this code to overload ++ operator to increment class variables i and x by one.. It does the job but the compiler showed these warnings:

Warning 1 warning C4620: no postfix form of 'operator ++' found for type 'tclass', using prefix form c:usersahmeddesktopcppqcppqcppq.cpp 25

Warning 2 warning C4620: no postfix form of 'operator ++' found for type 'tclass', using prefix form c:usersahmeddesktopcppqcppqcppq.cpp 26

This is my code:

class tclass{
public:
    int i,x;
    tclass(int dd,int d){
        i=dd;
        x=d;
    }
    tclass operator++(){

        i++;
        x++;
        return *this;

    }
};

int main() {
    tclass rr(3,3);
    rr++;
    rr++;
    cout<<rr.x<<" "<<rr.i<<endl;
    system("pause");
    return 0;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This syntax:

tclass operator++()

is for prefix ++ (which is actually normally written as tclass &operator++()). To distinguish the postfix increment, you add a not-used int argument:

tclass operator++(int)

Also, note that the prefix increment better return tclass & because the result may be used after: (++rr).x.

Again, note that the postfix increment looks like this:

tclass operator++(int)
{
    tclass temp = *this;
    ++*this;     // calls prefix operator ++
                 // or alternatively ::operator++(); it ++*this weirds you out!!
    return temp;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...