# C++结课考试 ZZU选修

### 1 实现抽象类

#include <iostream>
#include <cmath>
using namespace std;
const double PI = acos(-1.0);
class CShape {
public:
virtual double getArea() = 0;
virtual void setData(CShape *p) = 0;
};
class CRect: public CShape {
private:
double w, h;
public:
CRect(double w = 0.0, double h = 0.0):w(w),h(h){}
double getArea() {
return w * h;
}
void setData(CShape *p) {
this->w = ((CRect*)p)->w;
this->h = ((CRect*)p)->h;
}
void hello() {
cout << "hello" << endl;
}
};
class CCircle:public CShape {
private:
double r;
public:
CCircle(double r = 0):r(r){}
double getArea() {
return PI * r * r;
}
void setData(CShape *p) {
this->r = ((CCircle*)p)->r;
}
};
class CArea {
public:
double getAreaSum(CShape &a, CShape &b) {
return a.getArea() + b.getArea();
}
};
int main()
{
CShape *p, *q;
p = new CRect(4, 5);
CRect tmp = CRect(2, 5); //taking address of temporary
p->setData(&tmp);
q = new CCircle(1.0);
CArea c;
cout << c.getAreaSum(*p, *q) << endl;
((CRect*)p)->hello();

delete p, q;

return 0;
}

### 2 重载++运算符

#include <iostream>
using namespace std;
class Clock {
private:
int hour, minute, second;
public:
Clock(int hour=0, int minute=0, int second=0);
void showTime()const; //常量成员函数，不能修改数据（？什么数据）
Clock & operator++();
Clock operator++(int);
~Clock(){cout<<"gc"<<endl;} //重写GC，是为了查看重载前置++时，返回引用于不返回引用的区别
};
Clock::Clock(int hour, int minute, int second) {
if(0 <= hour && hour < 24 && 0 <= minute && minute < 60 && 0 <= second && second < 60) {
this->hour = hour;
this->minute = minute;
this->second = second;
}
else {
cout << "Time error" << endl;
}
}
void Clock::showTime() const {
cout << hour << ":" << minute << ":" << second << endl;
}
Clock & Clock::operator++() {
second++;
if(second >= 60) {
second -= 60;
minute++;
if(minute >= 60) {
minute -= 60;
hour++;
hour %= 24;
}
}
return *this;
}
Clock Clock::operator++(int) { //后置++，使用了前置++实现
Clock old = *this;
++(*this);
return old;
}

int main()
{
Clock myClock(23, 59, 59);
myClock.showTime(); //23:59:59
(myClock++).showTime(); //23:59:59
myClock.showTime(); //0:0:0
(++myClock).showTime(); //0:0:1
myClock.showTime(); //0:0:1

return 0;
}
/*

23:59:59
gc
23:59:59
gc
0:0:0
0:0:1
gc
0:0:1
gc

23:59:59
23:59:59
gc
0:0:0
0:0:1
0:0:1
gc
*/

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120