面向对象程序设计
1请使用函数模板 #include <iostream> using namespace std; template <typename T1,typename T2> void m(T1 a,T2 b){ if(a>=b) cout<<a<<endl; else cout<<b<<endl; } int main() { int a=1; float b=2.3; double c=4.5; m(a,b); m(a,c); m(b,c); return 0; }
2按下列要求定义模板 #include <iostream> #include<string> using namespace std; template <class T1,class T2> class com{ public: com(T1 newx,T2 newy){x=newx;y=newy;} void print(){cout<<x<<" "<<y<<endl;} private: T1 x; T2 y; }; int main() { int age; double score; double wage; string title; cin>>age>>score>>wage>>title; com<int,double> student(age,score); com<double,string> teacher(wage,title); student.print(); teacher.print(); return 0;
3定义一个Dog类,包含体重 #include <iostream> #include <fstream> using namespace std; class Dog { public:Dog(int weight, long days) :itsWeight(weight), itsNumberDaysAlive(days) {} ~Dog() {} int getWeight() {return itsWeight;} long getDaysAlive() {return itsNumberDaysAlive;} private: int itsWeight; long itsNumberDaysAlive; }; int main() { char fileName[80]; cin >> fileName; ofstream fout(fileName); Dog dog1(5, 10); fout.write((char*) &dog1, sizeof dog1); fout.close(); ifstream fin(fileName); Dog dog2(2, 2); // cout << "dog2 weight: " << dog2.getWeight() << endl; // cout << "dog2 days: " << dog2.getDaysAlive() << endl; fin.read((char*) &dog2, sizeof dog2); cout << "dog2 weight:" << dog2.getWeight() << endl; cout << "dog2 days:" << dog2.getDaysAlive() << endl; fin.close(); return 0; }
4定义一个dog类,包含了age #include <iostream>using namespace std;class Dog {public:Dog(int newAge = 0, int newWeight = 5);~Dog();int getAge() {return age;}void setAge(int newAge) {age = newAge;}int getWeight() {return weight;}void setWeight(int newWeight) {weight = newWeight;}private:int age, weight;};Dog::Dog(int newAge, int newWeight) {age = newAge;weight = newWeight;}Dog::~Dog() //析构函数,不做任何工作{}int main() {Dog Jack(2, 10);cout << "Jack is a Dog who is ";cout << Jack.getAge() << " years old and " << Jack.getWeight() << " pounds weight." <<endl;Jack.setAge(7);Jack.setWeight(20);cout << "Now Jack is ";cout << Jack.getAge() << " years old and " << Jack.getWeight() << " pounds weight." <<endl;return 0;}
5定义一个基类BassClass .#include<iostream> using namespace std; class BaseClass{ public:void fn1(){cout<<"BaseClass::fn1"<<endl;} void fn2(){cout<<"BaseClass::fn2"<<endl;} private: }; class DerivedClass:public BaseClass{ public: void fn1(){cout<<"DerivedClass::fn1"<<endl;} void fn2(){cout<<"DerivedClass::fn2"<<endl;} }; int main(){ DerivedClass derivedclass; derivedclass.fn1(); derivedclass.fn2(); DerivedClass *d=&derivedclass; d->fn1(); d->fn2(); BaseClass *b=&derivedclass; b->fn1(); b->fn2(); return 0;}
6定义一个抽象类Shape #include<iostream> using namespace std; class Shape { public: virtual double getArea()=0; }; class Circle:public Shape {public: Circle(double nr){r=nr;} double getArea(); private: double r; }; class Rectangle:public Shape {public: Rectangle(double nlen,double nwidth){len=nlen;width=nwidth;} double getArea(); private: double len,width; }; double Circle::getArea(){return 3.14*r*r;} double Rectangle::getArea(){return len*width;} int main() { Circle c(5); Rectangle r(3.4,4.5); Shape *pc=&c;; Shape *pr=&r; cout<<pc->getArea()<<endl; cout<<pr->getArea()<<endl; return 0; }
7定义Boat与Car#include <iostream> using namespace std; class Boat; class Car { private: int weight; public: Car(int j) { weight = j; } friend int getTotalWeight(Car &aCar, Boat &aBoat); }; class Boat { private: int weight; public: Boat(int j) { weight = j; } friend int getTotalWeight(Car &aCar, Boat &aBoat); }; int getTotalWeight(Car &aCar, Boat &aBoat) { return aCar.weight + aBoat.weight; } int main() { Car c1(4); Boat b1(5); cout << getTotalWeight(c1, b1) << endl; return 0; }
8定义一个哺乳动物类 #include <iostream> #include<string> using namespace std; class Mammal { public: Mammal(int a,int w); ~Mammal(); private: int itsAge; int itsWeight; }; class Dog: public Mammal { public: Dog(int a,int w,string color); ~Dog(); private: string itsColor; }; Mammal::Mammal(int a,int w) : itsAge(a), itsWeight(w) { cout << "Mammal constructor\n"; } Mammal::~Mammal() { cout << "Mammal destructor\n"; } Dog::Dog(int a,int w,string color) : Mammal(a,w),itsColor(color) { cout << "Dog constructor\n"; } Dog::~Dog() { cout << "Dog destructor\n"; } int main() { Dog jack(5,25,"white"); return 0; }
9定义一个Employee #include <iostream> #include <string> using namespace std; class Employee { private: string name; string street; string city; string zip; public: Employee(string newname, string str, string ct, string z); void setName(string n); void display(); }; Employee::Employee (string newname, string str, string ct, string z) { name=newname; street=str; city=ct; zip=z; } void Employee::setName (string n) { name=n; } void Employee::display () { cout << name << " "<<street << " "; cout << city << " "<< zip; } int main() { Employee e1("张三","平安大街3号", "北京", "100000"); e1.display(); cout << endl; e1.setName("李四"); e1.display(); cout << endl; }
10定义一个Shape #include <iostream> using namespace std; class Shape { public: Shape(){} ~Shape(){} 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(){}; float getArea() { return itsLength * itsWidth; } private: float itsWidth; float itsLength; }; class Square : public Rectangle { public: Square(float len); ~Square(){} }; Square::Square(float len): Rectangle(len, len) { } int main() { Shape s1; cout << "The area of the Shape is " << s1.getArea () << endl; Rectangle s2(4,6); cout << "The area of the Rectangle is " << s2.getArea() << endl; Square s3(5); cout << "The area of the Square is " << s3.getArea() << endl; return 0; }
11编写一个计数器 #include <iostream> using namespace std; class Counter { public: Counter(); Counter(int newValue); ~Counter(){} int getValue(){ return value; } Counter operator+ (Counter &); private: int value; }; Counter::Counter(int initialValue):value(initialValue){} Counter::Counter():value(0){} Counter Counter::operator+ (Counter & rhs) { return Counter(value + rhs.value); } int main() { Counter varOne(2), varTwo(4), varThree; varThree = varOne + varTwo; cout << "varOne:" << varOne.getValue()<< endl; cout << "varTwo:" << varTwo.getValue() << endl; cout << "varThree:" << varThree.getValue() << endl; return 0;
12定义一个Cat类 #include <iostream> using namespace std; class Cat { public: Cat(int newage) { age=newage; numOfCats++; } ~Cat() { numOfCats--; } static int getNumOfCats() { return numOfCats; } private: int age; static int numOfCats; }; int Cat::numOfCats = 0; void telepathicFunction() { cout << "There are " << Cat::getNumOfCats() << " cats alive!\n"; } int main() { Cat a(2),b(3); telepathicFunction(); return 0; }
13定义一个Object类 #include <iostream> using namespace std; class Object { private: int weight; public: Object() { cout << "构造Object对象" << endl; weight = 0; } ~Object() { cout << "析构Object对象" << endl; } }; class Box: public Object { private: int height, width; public: Box() { cout << "构造Box对象" << endl; height = width = 0; } ~Box() { cout << "析构Box对象" << endl; } }; int main() { Box a; return 0; }
14定义一个树类 #include <iostream> using namespace std; 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; } int main() { Tree t(12); t.age(); t.grow(4); return 0; }
15实现一个名Simple #include <iostream> using namespace std; class SimpleCircle { public: SimpleCircle(); SimpleCircle(int); SimpleCircle(const SimpleCircle &); ~SimpleCircle() {delete itsRadius;} void setRadius(int); int getRadius() const; private: int *itsRadius; }; SimpleCircle::SimpleCircle() { itsRadius = new int(5); } SimpleCircle::SimpleCircle(int radius) { itsRadius = new int(radius); } SimpleCircle::SimpleCircle(const SimpleCircle & rhs) { int val = rhs.getRadius(); itsRadius = new int(val); } int SimpleCircle::getRadius() const { return *itsRadius; } int main() { SimpleCircle CircleOne, CircleTwo(9); SimpleCircle CircleThree(CircleOne); cout << "CircleOne:" << CircleOne.getRadius() << endl; cout << "CircleTwo:" << CircleTwo.getRadius() << endl; cout << "CircleThree:" << CircleThree.getRadius() << endl; return 0; }
16定义一个人类 #include<string> #include<iostream> using namespace std; class Person { public: Person(string nam, char s, int a) { name = nam; sex = s; age = a; } protected: string name; char sex; int age; }; class Teacher:virtual public Person { public: Teacher(string nam, char s, int a, string t):Person(nam, s, a) { title = t; } protected: string title; }; class Student:virtual public Person { public: Student(string nam, char s, int a, float sco):Person(nam, s, a), score(sco){} protected: float score; }; class Graduate:public Teacher, public Student { public: Graduate(string nam, char s, int a, string t, float sco, float w): Person(nam, s, a), Teacher(nam, s, a, t),Student(nam, s, a, sco), wage(w) {} void show() { cout << "name:" << name << endl; cout << "sex:" << sex << endl; cout << "age:" << age << endl; cout << "title:" << title << endl; cout << "score:" << score << endl; cout << "wage:" << wage << endl; } private: float wage; }; int main(void) { Graduate grad1("Wang_li", 'f', 24, "assistant", 89.5, 2400); grad1.show(); return 0; }=
17运算符前置和后置
#include<iostream>
using namespace std;
class Clock{
public:
Clock(int h,int m,int s)
{
hour=h;minute=m;second=s;
}
Clock operator ++(){
second+=1;
if(second>=60)
{
second-=60;
minute+=1;
if(minute>=60)
{
minute-=60;
hour+=1;
if(hour==24)
hour=0;
}
}
return *this;
}
Clock operator++(int){
Clock old=*this;
++(*this);
return old;
}
void show(){
cout<<hour<<":"<<minute<<":"<<second<<endl;
}
private:
int hour,minute,second;
};
int main()
{
Clock first(23,59,59);
first.show();
(first++).show();
(++first).show();
return 0;
}
18复数C #include <iostream> using namespace std; class Complex { public: Complex(double r, double i) { real=r; image=i; } Complex(double r) { real=r; image=0; } void show(); void add(Complex c2); private: double real; double image; }; void Complex::add(Complex c2) { real += c2.real; image += c2.image; } void Complex::show() { cout << real << "+"; cout << image << "i"; cout << endl; } int main() { Complex c1(3, 5); Complex c2 = 4.5; c1.show(); c1.add(c2); c1.show(); return 0; }
19重载C #include<iostream> using namespace std; class Complex{ public:Complex(double newa=0,double newb=0){a=newa;b=newb;} friend ostream &operator<<(ostream &out,Complex &i); friend Complex operator+(Complex &i,Complex &j); friend Complex operator-(Complex &i,Complex &j); private:double a,b; }; Complex operator+(Complex &i,Complex &j){ double x=i.a+j.a;double y=i.b+j.b;Complex c(x,y);return c;} Complex operator-(Complex &i,Complex &j){ double x=i.a-j.a;double y=i.b-j.b;Complex c(x,y);return c;} ostream &operator<<(ostream &out,Complex &i){ out<<"("<<i.a<<", "<<i.b<<")";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; }
20Rectangle矩形 #include<iostream> using namespace std; class Point { public: Point(int newx,int newy) { x=newx; y=newy; } Point(Point &p) { x=p.x; y=p.y; } int getX(){return x;} int getY(){return y;} private: int x,y; }; class Ractangle { public: Ractangle(Point a,Point b); Ractangle(Ractangle &r); float getArea(){return area;} private: Point a,b; float area; }; Ractangle::Ractangle(Point newa,Point newb):a(newa),b(newb) { double x,y; x=static_cast<double>(a.getX()-b.getX()); y=(double)(a.getY()-b.getY()); area=(double)(x*y); } Ractangle::Ractangle(Ractangle &r):a(r.a),b(r.b) { area=r.area; } int main() { Point p1(1,2),p2(3,4); Ractangle juxing1(p1,p2); Ractangle juxing2(juxing1); cout<<juxing1.getArea()<<endl; cout<<juxing2.getArea()<<endl; return 0; }
21编程Document #include <iostream> #include <string> using namespace std; class Document { public: Document(string nm); void PrintNameOf(); // Print name. private: string name; // Document name. }; Document::Document(string nm) { name = nm; }; void Document::PrintNameOf() { cout << "Name of document:"; cout << name << endl; } class Book: public Document { public: Book(string nm, long pagecount); void PrintNameOf(); private: long pageCount; }; Book::Book(string nm, long pagecount) : Document(nm) { pageCount = pagecount; } void Book::PrintNameOf() { Document::PrintNameOf(); cout<<"(备注:book)"<<endl; } int main() { Document a("Document1"); Book b("三国演义", 100); a.PrintNameOf(); b.PrintNameOf(); return 0; }
22钟表类 #include<iostream> using namespace std; class Clock{ public: void setTime(int newh,int newm,int news) { hour=newh; minute=newm; second=news; } void showTime() { cout<<hour<<":"<<minute<<":"<<second<<endl; } private: int hour; int minute; int second; }; int main() { Clock myclock; myclock.setTime(18,17,16); myclock.showTime(); return 0; }