HOUR 15 Operator Overloading

自增运算符的重载:

#include <QCoreApplication>
#include <iostream>
using namespace std;

class Counter
{
public:
    Counter();
    ~Counter() {};
    int getValue() const {return value;}
    void setVlue(int x) { value = x;}
    void increment() { ++value;}
    const Counter& operator++();
    const Counter operator++(int);

private:
    int value;
};

Counter::Counter():
    value(0)
{}

const Counter& Counter::operator++()
{
    ++value;
    return *this;

}

const Counter Counter::operator++(int)
{
    Counter temp(*this);
    ++value;
    return temp;
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    Counter c;
    std::cout << "The value of c is " << c.getValue()
              << std::endl;
    c.increment();
    std::cout << "The value of c is " << c.getValue()
              << std::endl;
    ++c;
    std::cout << "The value of c is " << c.getValue()
              << std::endl;
    Counter b = ++c;
    std::cout << "The value of a: " << b.getValue();
    std::cout << " and c: " << c.getValue() << std::endl;
    std::cout << endl << endl;

    std::cout << "the value of c is: " << c.getValue()
              << std::endl;



    Counter fuck = c;
    std::cout << "the value of fuck is: " << fuck.getValue()
              << std::endl;

    std::cout << "perform fuck = c++" << std::endl;
    fuck = c++;
    std::cout << "the value of c is: " << c.getValue()
              << std::endl;;

    std::cout << "the value of fuck is: " << fuck.getValue()
              << std::endl;

    return a.exec();
}

 

posted @ 2018-03-22 19:39  一只大公鸡  阅读(110)  评论(0)    收藏  举报