counter a=*this; ++(*this); return a; }
counter counter::operator --() //前置--实现 { --P; return *this; }
counter counter::operator --(int) //后置--实现 { counter a=*this; --(*this); return a; }
istream& operator>>(istream& is,counter& a) //运算符>>实现 { is>>a.P; return is; }
ostream& operator<<(ostream& os,counter& a) //运算符<<实现 { os< int main() { counter c1(5),c2(3); cout<<\ cout<<\测试自增自减功能 cout<<\ cout<<\ cout<<\ system(\ return 0; } Part1 7运行结果与分析: 运行结果分析: 定义c1的值为5,c2的值为3; 此时++c1的数值为6;c1++输出时为6,输出后为7; 此时c2—输出时为3;--c2输出时为1,输出后为1; 输出结果正确。 Part1 7设计过程、思路与分析: 1.定义counter类,私有成员数据weight,设置其成员函数(构造函数和析构函数) 2.重载自加自减运算符和<<、>>运算符。 3.在主函数中实现运算符重载。 4.友元函数需要声明。 ===================================================================== Part1 8 : 虚函数和抽象类:定义一个抽象类shape,包括公有的计算面积area 函数,计算体积volume函数,输出基本信息函数printinfo(三个函数均为纯虚函数)。从shape公有派生point类,增加私有数据成员x,y坐标,以及构造函数,析构函数。从point公有派生circle类,增加私有数据成员半径r,以及构造函数,析构函数。从circle公有派生cylinder类,增加私有数据成员高度h,以及构造函数,析构函数。(在定义三个派生类的过程中,自己考虑需要重定义哪个虚函数)。在main函数中,定义shape类的指针,指向派生类的对象,输出三类对象的基本信息,面积,体积;(将shape指针改为引用再尝试)。 #include class shape { public: virtual double area() = 0; virtual double volume() = 0; virtual void printinfo () = 0; }; class point :public shape { public: point() {} point(double x, double y) { this->x = x; this->y = y; } void printinfo() { cout << \ } ~point() {} private: double x; double y; }; class circle :public point { public: circle() {} circle(double r,double x,double y):point(x,y) { this->r = r; } double area() { return P*r*r; } void printinfo() { point::printinfo(); cout << \ cout << \ } ~circle() {} private: double r; }; class cylinder :public circle { public: cylinder() {} cylinder(double h, double x,double y, double r) :circle(x, y,r) { this->h = h; } double volume() { return h*circle::area(); } void printinfo() { circle::printinfo(); cout << \ cout << \ } ~cylinder() {} private: double h; }; int main() { cylinder c1(5, 2, 2, 3); shape *s; //指针 s = &c1; (*s).printinfo(); cout << \ cout << \ system(\ return 0; } Part1 8运行结果与分析: 运行结果: 运行结果分析: 在主函数中分别用了shape类的指针和引用,输出结果正确。 Part1 8设计过程、思路与分析: 4.先定义基类shape。设置三个纯虚函数并且声明:virtual double area()=0; //声明计算面积纯虚函数area();virtual void volume()=0; //声明计算体积纯虚函数volume();virtual void printinfo()=0; //声明输出基本信息纯虚函数printinfo(); 5.定义类point共有继承自类shape。并且在该类中实现三个纯虚函数。 6.定义类circle共有继承自类point。并且在该类中实现三个纯虚函数。 7.定义类cylinder共有继承自类circle。并且在该类中实现三个纯虚函数。 8.在主函数中分别创建类point的对象a,circle的对象b,cylinder的对象c,并初始化; 9.在主函数中分别定义shape类的指针和引用,调用printinfo()函数。 ===================================================================== Part1 9 : 模板:设计一个堆栈的类模板Stack,在模板中用类型参数T表示栈 中存放的数据,用非类型参数MAXSIZE代表栈的大小。 #include template public: Stack(); bool full(); bool empty(); void push(T element); T gettop(); void pop(); ~Stack() { delete[]ptr; } private: int maxsize; int pos; T *ptr; }; template
相关推荐: