
class Rectangle // 定义一个Rectangle类
{
public:
Rectangle() {itsLength=1,itsWidth=2;}
Rectangle(int length ,int width) {itsLength=length;itsWidth=width;}
~Rectangle() {}
int GetLength() {return itsLength;}
int GetWidth() {return itsWidth;}
private:
int itsLength,itsWidth; //有长itsWidth、宽itsLength等属性
};
2. 定义计数器Counter类,对其重载运算符 + 。
class counter
{
private:
int i;
public:
counter(){}
counter(int p){i=p;}
~counter(){}
int geti()
{return i;
}
void seti(int p)
{i=p;
}
counter operator+(counter &r)
{return counter(i+r.geti());
}
};
3、定义一个异常类CException,有成员函数Reason(),用来显示异常的类型,定义函数fn1()触发异常,在主函数的try模块中调用fn1(),在catch模块中捕获异常,观察程序的执行流程。
#include using namespace std; enum{EXCEPTION_1 = 1, EXCEPTION_2, EXCEPTION_3}; class CException{ public: CException(int nReason) { m_nReason = nReason; } ~CException() {} void Reason() { cout <<"Exception:"<< m_nReason << endl; } private: int m_nReason; }; void fn1(){ throw new CException(EXCEPTION_1); } int main(){ try{ fn1(); } catch(CException* e){ e->Reason(); } return 0; } 4、定义一个Shape基类,在此基础上派生出Rectangle和Circle,二者都有GetArea()函数计算对象的面积。使用Rectangle类创建一个派生类Square。 class Shape//基类 { public: Shape(){} ~Shape(){} virtual float GetArea()=0; }; class Circle:public Shape { private: float itsRadius; public: Circle(float radius):itsRadius(radius){} ~Circle(){} float GetArea(){return PI*itsRadius*itsRadius;} }; class Rectangel:public Shape { private: float itsLength,itsWidth; public: Rectangel(){} Rectangel(float len,float width):itsLength(len),itsWidth(width){} ~Rectangel() {} virtual float GetArea(){return itsLength*itsWidth;} }; class Square:public Rectangel { private: float Widelength; public: Square(float wl):Widelength(wl){} ~Square(){} virtual float GetArea(){return Widelength*Widelength;} }; 5、定义一个基类BaseClass,从它派生出类DerivedClass,BaseClass有成员函数fn1()、fn2(),DerivedClass也有成员函数fn1()、fn2(),在主程序中定义一个DerivedClass的对象,分别用DerivedClass的对象以及BaseClass和DerivedClass的指针来调用fn1()、fn2(),观察运行结果。 #include class BaseClass { public: virtual void fn1(); void fn2(); }; void BaseClass::fn1() { cout << "调用基类的虚函数 fn1()" << endl; } void BaseClass::fn2() { cout << "调用基类的非虚函数 fn2()" << endl; } class DerivedClass : public BaseClass { public: void fn1(); void fn2(); }; void DerivedClass::fn1() { cout << "调用派生类的函数 fn1()" << endl; } void DerivedClass::fn2() { cout << "调用派生类的函数 fn2()" << endl; } void main() { DerivedClass aDerivedClass; DerivedClass *pDerivedClass = &aDerivedClass; BaseClass *pBaseClass = &aDerivedClass; pBaseClass->fn1(); pBaseClass->fn2(); pDerivedClass->fn1(); pDerivedClass->fn2(); } 6、定义一个Employee类,其中包括表示姓名、街道地址、城市和邮编等属性,包括chage_name()和display()等函数;display()使用cout语句显示姓名、街道地址、城市和邮编等属性,函数change_name()改变对象的姓名属性,实现并测试这个类。 #include #include class Employee { private: char name[30]; char street[30]; char city[18]; char zip[6]; public: Employee(char *n, char *str, char *ct, char *z); void change_name(char *n); void display(); }; Employee::Employee (char *n,char *str,char *ct, char *z) { strcpy(name, n); strcpy(street, str); strcpy(city, ct); strcpy(zip, z); } void Employee::change_name (char *n) { strcpy(name, n); } void Employee::display () { cout << name << " " << street << " "; cout << city << " "<< zip; } void main(void) { Employee e1("张三平安大街 3 号", "北京", "100000"); e1.display(); cout << endl; e1.change_name("李四"); e1.display(); cout << endl; } 7、 #include class Boat; class Car { private: int weight; public: Car(int j){weight = j;} friend int totalWeight(Car &aCar, Boat &aBoat); }; class Boat { private: int weight; public: Boat(int j){weight = j;} friend int totalWeight(Car &aCar, Boat &aBoat); }; int totalWeight(Car &aCar, Boat &aBoat) { return aCar.weight + aBoat.weight; } void main() { Car c1(4); Boat b1(5); cout << totalWeight(c1, b1) << endl; } 8、 #include #include using namespace std; int getpower(int x,int y) { return pow(x,y); } double getpower(double x,int y) { return pow(x,y); } int main() { int a,m;double b; cout<<"请输入整数a和m实数b"< { cin>>a>>m>>b; cout<<"a^m="< return 0; } 9、一圆型游泳池如图所示,现在需在其周围建一圆型过道,并在其四周围上栅栏。栅栏价格为35元/米,过道造价为20元/平方米。过道宽度为3米,游泳池半径由键盘输入。要求编程计算并输出过道和栅栏的造价。 #include using namespace std; class Circle { private: float r; public: Circle():PI(3.1415926) { r=0; } Circle(float r):r(r),PI(3.1415926) { } void printInfor() { cout<<"r:"< void Girth(float r) { float c; c=2*PI*(r+3); cout<<"周长c:"< void Area(float r)//小圆面积 { float s1; s1=PI*r*r; cout<<"面积s1:"< float s2; s2=PI*(r+3)*(r+3); cout<<"面积s2:"< const double PI; }; int main() { Circle c1; float r; c1.printInfor() ; cout<<"please input r"< c1.Girth(r); cout< cout< return 0; } 10、设某次体育比赛的结果有4中可能,胜(win)、负(lose)、平局(tie)、比赛取消(cancel),编写程序顺序输出这四种情况(使用枚举类型) #include using namespace std; enum GameResult{WIN ,LOSE ,TIE ,CANCEL}; int main() { GameResult result;///声明变量时,可以不写关键字enum enum GameResult omit=CANCEL;///也可以在类型名前写enum for(int count=WIN; count<=CANCEL;count++)///隐含类型转换 { result=GameResult(count);///显示类型转换 if(result==omit) cout<<"The game was cancelled"< { cout<<"The game was played"; if(result==WIN) cout<<"and we won!"< cout<<"and we lost."< cout<<"and we tie."< } return 0; } 11、编写一个求x的n次方的函数 void power(int x, int n) { int s = 1; for (int i = 1; i <= n; i++) { s = s*x; } cout << s< 12、将“+”、“-”运算重载为复数类的成员函数 ●规则: 实部和虚部分别相加减。 ●操作数: 两个操作数都是复数类的对象。 class Complex { public: Complex(double r = 0.0, double i = 0.0) : real(r), imag(i) { } //运算符+重载成员函数 Complex operator + (const Complex &c2) ; //运算符-重载成员函数 Complex operator - (const Complex &c2) ; void display() ; //输出复数 private: double real; //复数实部 double imag; //复数虚部 }; Complex Complex::operator+(const Complex &c2) { //创建一个临时无名对象作为返回值 return Complex(real+c2.real, imag+c2.imag); } Complex Complex::operator-(const Complex &c2) { //创建一个临时无名对象作为返回值 return Complex(real-c2.real, imag-c2.imag); } void Complex::display() { cout<<"("< 13、 运算符前置++和后置++重载为时钟类的成员函数。 ●前置单目运算符,重载函数没有形参,对于后置单目运算符,重载函数需要有一个整型形参。 ●操作数是时钟类的对象。 ●实现时间增加1秒钟。 class Clock //时钟类声明 { public: //外部接口 Clock(int NewH=0, int NewM=0, int NewS=0); void ShowTime(); Clock& operator ++(); //前置单目运算符重载 Clock operator ++(int); //后置单目运算符重载 private: //私有数据成员 int Hour, Minute, Second; }; Clock::Clock(int NewH, int NewM, int NewS) { if (0<=NewH && NewH<24 &&0<=NewM && NewH<60 &&0<=NewS && NewS<60) { Hour=NewH; Minute=NewM; Second=NewS; } else cout << "Tine error!"< void Clock::ShowTime() { cout << Hour <<":"<< Minute<<":"< Clock& Clock::operator ++() //前置单目运算符重载函数 { Second++; if(Second>=60) { Second=Second-60; Minute++; if(Minute>=60) { Minute=Minute-60; Hour++; Hour=Hour%24; } } return *this; } Clock Clock::operator ++(int) //后置单目运算符重载 { Clock old=*this; ++(*this); return old; } 14、. 将+、-(双目)重载为非成员函数,并将其声明为复数类的友元,两个操作数都是复数类的常引用。 将<<(双目)重载为非成员函数,并将其声明为复数类的友元,它的左操作数是std::ostream引用,右操作数为复数类的常引用,返回std::ostream引用,用以支持下面形式的输出: cout << a << b; 该输出调用的是:operator << (operator << (cout, a), b); #include using namespace std; class Complex { public: Complex(double r = 0.0, double i = 0.0) : real(r), imag(i) { } friend Complex operator+(const Complex &c1, const Complex &c2); friend Complex operator-(const Complex &c1, const Complex &c2); friend ostream & operator<<(ostream &out, const Complex &c); private: double real; //复数实部 double imag; //复数虚部 }; Complex operator+(const Complex &c1, const Complex &c2){ return Complex(c1.real + c2.real, c1.imag + c2.imag); } Complex operator-(const Complex &c1, const Complex &c2){ return Complex(c1.real - c2.real, c1.imag - c2.imag); } ostream & operator<<(ostream &out, const Complex &c){ out << "(" << c.real << ", " << c.imag << ")"; return out; } int main() { Complex c1(5, 4), c2(2, 10), c3; cout << "c1 = " << c1 << endl; cout << "c2 = " << c2 << endl; c3 = c1 - c2; //使用重载运算符完成复数减法 cout << "c3 = c1 - c2 = " << c3 << endl; c3 = c1 + c2; //使用重载运算符完成复数加法 cout << "c3 = c1 + c2 = " << c3 << endl; return 0; } 16.虚基类例题 17.文件打开,关闭,读、写例题。 第三章: #include long GetPower(int x, int y); int main() { int number, power; long answer; cout << "Enter a number: "; cin >> number; cout << "To what power? "; cin >> power; answer = GetPower(number,power); cout << number << " to the " << power << "th power is " < } long GetPower(int x, int y) { if(y == 1) return x; else return (x * GetPower(x,y-1)); } 第四章: #include class Tree { int ages; public: Tree(int n=0); ~Tree(); void grow(int years); void age(); }; Tree::Tree(int n) { ages = n; } Tree::~Tree() { age(); } void Tree::grow(int years) { ages += years; } void Tree::age() { cout << "这棵树的年龄为" << ages << endl; } void main() { Tree t(12); t.age(); t.grow(4); } 第五章: #include class Boat; class Car { private: int weight; public: Car(int j){weight = j;} friend int totalWeight(Car &aCar, Boat &aBoat); }; class Boat { private: int weight; public: Boat(int j){weight = j;} friend int totalWeight(Car &aCar, Boat &aBoat); }; int totalWeight(Car &aCar, Boat &aBoat) { return aCar.weight + aBoat.weight; } void main() { Car c1(4); Boat b1(5); cout << totalWeight(c1, b1) << endl; } 程序运行输出:9 第六章: 定义一个Employee类,其中包括表示姓名、街道地址、城市和邮编等属性,包括chage_name()和display()等函数;display()使用cout语句显示姓名、街道地址、城市和邮编等属性,函数change_name()改变对象的姓名属性,实现并测试这个类。 #include #include class Employee { private: char name[30]; char street[30]; char city[18]; char zip[6]; public: Employee(char *n, char *str, char *ct, char *z); void change_name(char *n); void display(); }; Employee::Employee (char *n,char *str,char *ct, char *z) { strcpy(name, n); strcpy(street, str); strcpy(city, ct); strcpy(zip, z); } void Employee::change_name (char *n) { strcpy(name, n); } void Employee::display () { cout << name << " " << street << " "; cout << city << " "<< zip; } void main(void) { Employee e1("张三平安大街3号", "北京", "100000"); e1.display(); cout << endl; e1.change_name("李四"); e1.display(); cout << endl; } 程序运行输出: 张三 平安大街3号 北京 100000 李四 平安大街3号 北京 100000 第七章: (1)定义一个Shape基类,在此基础上派生出Rectangle和Circle,二者都有GetArea()函数计算对象的面积。使用Rectangle类创建一个派生类Square。 (2)定义一个基类BaseClass,从它派生出类DerivedClass,BaseClass有成员函数fn1()、fn2(),DerivedClass也有成员函数fn1()、fn2(),在主程序中定义一个DerivedClass的对象,分别用DerivedClass的对象以及BaseClass和DerivedClass的指针来调用fn1()、fn2(),观察运行结果。 1. 源程序: #include class Shape { public: Shape(){} ~Shape(){} virtual float GetArea() { return -1; } }; class Circle : public Shape { public: Circle(float radius):itsRadius(radius){} ~Circle(){} float GetArea() { return 3.14 * itsRadius * itsRadius; } private: float itsRadius; }; class Rectangle : public Shape { public: Rectangle(float len, float width): itsLength(len), itsWidth(width){}; ~Rectangle(){}; virtual float GetArea() { return itsLength * itsWidth; } virtual float GetLength() { return itsLength; } virtual float GetWidth() { return itsWidth; } private: float itsWidth; float itsLength; }; class Square : public Rectangle { public: Square(float len); ~Square(){} }; Square::Square(float len): Rectangle(len,len) { } void main() { Shape * sp; sp = new Circle(5); cout << "The area of the Circle is " << sp->GetArea () << endl; delete sp; sp = new Rectangle(4,6); cout << "The area of the Rectangle is " << sp->GetArea() << endl; delete sp; sp = new Square(5); cout << "The area of the Square is " << sp->GetArea() << endl; delete sp; } 程序运行输出: The area of the Circle is 78.5 The area of the Rectangle is 24 The area of the Square is 25 2. 程序源码: #include class BaseClass { public: void fn1(); void fn2(); }; void BaseClass::fn1() { cout << "调用基类的函数fn1()" << endl; } void BaseClass::fn2() { cout << "调用基类的函数fn2()" << endl; } class DerivedClass : public BaseClass { public: void fn1(); void fn2(); }; void DerivedClass::fn1() { cout << "调用派生类的函数fn1()" << endl; } void DerivedClass::fn2() { cout << "调用派生类的函数fn2()" << endl; } void main() { DerivedClass aDerivedClass; DerivedClass *pDerivedClass = &aDerivedClass; BaseClass *pBaseClass = &aDerivedClass; aDerivedClass.fn1(); aDerivedClass.fn2(); pBaseClass->fn1(); pBaseClass->fn2(); pDerivedClass->fn1(); pDerivedClass->fn2(); } 程序运行输出: 调用派生类的函数fn1() 调用派生类的函数fn2() 调用基类的函数fn1() 调用基类的函数fn2() 调用派生类的函数fn1() 调用派生类的函数fn2() 后面章节: (1)定义一个Rectangle类,有长itsWidth、宽itsLength等属性,重载其构造函数Rectangle()和Rectangle(int width, int length)。 (2)定义计数器Counter类,对其重载运算符 + 。 (3)定义一个异常类CException,有成员函数Reason(),用来显示异常的类型,定义函数fn1()触发异常,在主函数的try模块中调用fn1(),在catch模块中捕获异常,观察程序的执行流程。 1. 解: 源程序: #include class Rectangle { public: Rectangle(); Rectangle(int width, int length); ~Rectangle() {} int GetWidth() const { return itsWidth; } int GetLength() const { return itsLength; } private: int itsWidth; int itsLength; }; Rectangle::Rectangle() { itsWidth = 5; itsLength = 10; } Rectangle::Rectangle (int width, int length) { itsWidth = width; itsLength = length; } int main() { Rectangle Rect1; cout << "Rect1 width: " << Rect1.GetWidth() << endl; cout << "Rect1 length: " << Rect1.GetLength() << endl; int aWidth, aLength; cout << "Enter a width: "; cin >> aWidth; cout << "\\nEnter a length: "; cin >> aLength; Rectangle Rect2(aWidth, aLength); cout << "\\nRect2 width: " << Rect2.GetWidth() << endl; cout << "Rect2 length: " << Rect2.GetLength() << endl; return 0; } 程序运行输出: Rect1 width: 5 Rect1 length: 10 Enter a width: 20 Enter a length: 50 Rect2 width: 20 Rect2 length: 50 2. 解: 源程序: typedef unsigned short USHORT; #include class Counter { public: Counter(); Counter(USHORT initialValue); ~Counter(){} USHORT GetItsVal()const { return itsVal; } void SetItsVal(USHORT x) {itsVal = x; } Counter operator+ (const Counter &); private: USHORT itsVal; }; Counter::Counter(USHORT initialValue): itsVal(initialValue) { } Counter::Counter(): itsVal(0) { } Counter Counter::operator+ (const Counter & rhs) { return Counter(itsVal + rhs.GetItsVal()); } int main() { Counter varOne(2), varTwo(4), varThree; varThree = varOne + varTwo; cout << "varOne: " << varOne.GetItsVal()<< endl; cout << "varTwo: " << varTwo.GetItsVal() << endl; cout << "varThree: " << varThree.GetItsVal() << endl; return 0; } 程序运行输出: varOne: 2 varTwo: 4 varThree: 6 3. 解: #include class CException { public: CException(){}; ~CException(){}; const char *Reason() const { return "CException类中的异常。"; } }; void fn1() { cout<< "在子函数中触发CException类异常" << endl; throw CException(); } void main() { cout << "进入主函数" << endl; try { cout << "在try模块中,调用子函数" << endl; fn1(); } catch( CException E ) { cout << "在catch模块中,捕获到CException类型异常:"; cout << E.Reason() << endl; } catch( char *str ) { cout << "捕获到其它类型异常:" << str << endl; } cout << "回到主函数,异常已被处理" << endl; } 程序运行输出: 进入主函数 在try模块中,调用子函数 在子函数中触发CException类异常 在catch模块中,捕获到CException类型异常:CException类中的异常。 回到主函数,异常已被处理
