1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
|
#include <iostream>
using namespace std;
class Number
{
private:
int num;
int twiceNum;
public:
Number(int n = 0);
Number(const Number & n);
void setNum(int n);
void setTwiceNum(int tn);
int getNum() const;
int getTwiceNum() const;
Number operator+ (const Number & r);
Number operator++ ();
Number operator++ (int);
friend void Reset(Number &t);
};
Number::Number(int n)
{
setNum(n);
}
Number::Number(const Number & n)
{
setNum(num=0 & twiceNum);
}
void Number::setNum(int n)
{
num = n;
twiceNum = 2 * n;
}
void Number::setTwiceNum(int tn)
{
if (tn % 2 == 0)
{
twiceNum = tn;
}
else
{
twiceNum = 0;
}
twiceNum = num / 2;
}
int Number::getNum() const
{
return num;
}
int Number::getTwiceNum() const
{
return twiceNum;
}
Number Number::operator+ (const Number & r)
{
Number sum;
sum.num = num + r.num;
sum.twiceNum = twiceNum + r.twiceNum;
&Number::setNum;
return sum;
}
Number Number::operator++ ()
{
++num;
&Number::setNum;
return *this;
}
Number Number::operator++ (int)
{
Number old(*this);
num++;
&Number::setNum;
return old;
}
void Reset(Number &t)
{
t.num = 0;
t.twiceNum = 0;
}
int main()
{
Number a, b(5), c(10);
Number d=c;
Number e;
cout<<"a: " <<a.getNum() << ", 2 X a: "<<a.getTwiceNum()<<endl;
cout<<"b: " <<b.getNum() << ", 2 X b: "<<b.getTwiceNum()<<endl;
cout<<"c: " <<c.getNum() << ", 2 X c: "<<c.getTwiceNum()<<endl;
cout<<"d: " <<d.getNum() << ", 2 X d: "<<d.getTwiceNum()<<endl;
cout <<endl;
Reset(b);
cout <<"After reset of b"<<endl;
cout<<"b: " <<b.getNum() << ", 2 X b: "<<b.getTwiceNum()<<endl;
cout <<endl;
b.setNum(7);
cout <<"After b.setNum(7)"<<endl;
cout<<"b: " <<b.getNum() << ", 2 X b: "<<b.getTwiceNum()<<endl;
cout <<endl;
b.setTwiceNum(21);
cout <<"After b.setTwiceNum(21)"<<endl;
cout<<"b: " <<b.getNum() << ", 2 X b: "<<b.getTwiceNum()<<endl;
cout <<endl;
b.setTwiceNum(30);
cout <<"After b.setTwiceNum(30)"<<endl;
cout<<"b: " <<b.getNum() << ", 2 X b: "<<b.getTwiceNum()<<endl;
cout <<endl;
a= b + c;
cout <<"After a= b+c"<<endl;
cout<<"a: " <<a.getNum() << ", 2 X a: "<<a.getTwiceNum()<<endl;
cout<<"b: " <<b.getNum() << ", 2 X b: "<<b.getTwiceNum()<<endl;
cout<<"c: " <<c.getNum() << ", 2 X c: "<<c.getTwiceNum()<<endl;
cout <<endl;
e= ++a;
cout <<"After e= ++a"<<endl;
cout<<"a: " <<a.getNum() << ", 2 X a: "<<a.getTwiceNum()<<endl;
cout<<"e: " <<e.getNum() << ", 2 X e: "<<e.getTwiceNum()<<endl;
cout <<endl;
e= a++;
cout <<"After e= a++"<<endl;
cout<<"a: " <<a.getNum() << ", 2 X a: "<<a.getTwiceNum()<<endl;
cout<<"e: " <<e.getNum() << ", 2 X e: "<<e.getTwiceNum()<<endl;
cout <<endl;
return 0;
}
|