1.基本类、构造函数、析构函数
例子:
1 #include <iostream>
2
3 class Tricycle
4 {
5 public:
6 Tricycle(int initialAge);
7 ~Tricycle();
8 int getSpeed();
9 void setSpeed(int speed);
10 void pedal();
11 void brake();
12 private:
13 int speed;
14 };
15
16 Tricycle::Tricycle(int speed)
17 {
18 std::cout<<"\nTricycle()\n";
19 setSpeed(speed);
20 }
21
22 Tricycle::~Tricycle()
23 {
24 std::cout<<"~Tricycle()\n";
25 }
26
27 int Tricycle::getSpeed()
28 {
29 return speed;
30 }
31
32 void Tricycle::setSpeed(int newSpeed)
33 {
34 if(newSpeed >=0)
35 {
36 speed = newSpeed;
37 }
38 }
39
40 void Tricycle::pedal()
41 {
42 setSpeed(speed + 1);
43 std::cout<<"\nPedaling;tricycle speed " <<getSpeed()<<" mph\n";
44 }
45
46 void Tricycle::brake()
47 {
48 setSpeed(speed - 1);
49 std::cout<<"\nBraking;tricycle speed "<<getSpeed()<<" mph\n";
50 }
51
52 int main()
53 {
54 Tricycle wichita(5);
55 wichita.pedal();
56 wichita.pedal();
57 wichita.brake();
58 wichita.brake();
59 wichita.brake();
60 return 0;
61 }
运行结果:
Tricycle()
Pedaling;tricycle speed 6 mph
Pedaling;tricycle speed 7 mph
Braking;tricycle speed 6 mph
Braking;tricycle speed 5 mph
Braking;tricycle speed 4 mph
~Tricycle()