Class 可以想像成一個物件類別。例如「馬達」、「底盤」,也可以是更抽象的概念,例如「路線」、「馬達控制算法」等等。Class 像是一個圖紙,定義了一個物件類別的屬性和能力。例如 底盤 的 class 的屬性可以有 包括所有底盤的馬達。能力可以有 arcade movement。這時就可以把 底盤 的 Class 定義為:
Copy // chassis.hpp
class Chassis {
public :
Chassis (std :: vector <okapi :: Motor > left , std :: vector <okapi :: Motor > right , float max_velocity = 200 );
void moveVelocity ( float left_vel , float right_vel);
void arcade ( float throttle , float turn);
private :
std :: vector < okapi :: Motor > left;
std :: vector < okapi :: Motor > right;
int max_velocity;
};
Copy // main.h
#include "chassis.hpp"
Copy // chassis.cpp
#include "main.h"
Chassis :: Chassis (std :: vector < okapi :: Motor > left , std :: vector < okapi :: Motor > right , float max_velocity) {
this -> left = left;
this -> right = right;
this -> max_velocity = max_velocity;
}
void Chassis :: moveVelocity ( float left_vel , float right_vel) {
for (okapi :: Motor left_motor : this -> left) {
left_motor . moveVelocity (left_vel);
}
for (okapi :: Motor right_motor : this -> right) {
right_motor . moveVelocity (right_vel);
}
}
void Chassis :: arcade ( float throttle , float turn) {
this -> moveVelocity ( this -> max_velocity * (throttle + turn) , this -> max_velocity * (throttle - turn));
}
Copy std :: vector < okapi :: Motor > left = {
okapi :: Motor ( 1 ) ,
okapi :: Motor ( 2 ) ,
};
std :: vector < okapi :: Motor > right = {
okapi :: Motor ( - 3 ) ,
okapi :: Motor ( - 4 ) ,
};
// create new chassis object
Chassis chassis = Chassis (left , right);
okapi :: Controller master (okapi :: ControllerId :: master );
okapi :: Motor left_motor ( 1 );
okapi :: Motor right_motor ( - 2 );
void opcontrol () {
while ( true ) {
// call arcade function in the chassis object
chassis . arcade ( master . getAnalog (okapi :: ControllerAnalog :: leftY) , master . getAnalog (okapi :: ControllerAnalog :: rightX));
pros :: delay ( 10 );
}
}