Intro to C++ for Robotics Made for ALARM. Computer System Hardware – cpu, memory, i/o Software –...
-
Upload
eric-sanders -
Category
Documents
-
view
221 -
download
1
Transcript of Intro to C++ for Robotics Made for ALARM. Computer System Hardware – cpu, memory, i/o Software –...
C++ - program structure
.h - Header files – contain definitions – aka signatures
.cc – contain the “code” or how to do what it does
Compiler Directives
#include – brings in definition files#define – sets up literal names for
unchanging values
C++ Basic Program structure
Main Where everything starts, creates and calls other
software until task is done. Statement
Ends in ; White space does not matter to the compiler, but
matter a LOT to the engineer. Compound statements are contained in { }
Attributes (aka variables) Methods (aka functions)
C++ Arithmetic OperatorsOperator Name Syntax
Unary Plus +a
Addition (Sum) a + b
Prefix Increment ++a
Postfix Increment a++
Assignment by Addition a += b
Unary Minus (Negation) -a
Subtraction (Difference) a - b
Prefix Decrement --a
Postfix Decrement a--
Assignment by Subtraction a -= b
Multiplication (Product) a * b
Assignment by Multiplication a *= b
Division (Quotient) a / b
Assignment by Division a /= b
Modulus (Remainder) a % b
Assignment by Modulus a %= b
C++ Comparison Operators
Operator Name Syntax
Less Than a < b
Less Than or Equal To a <= b
Greater Than a > b
Greater Than or Equal To a >= b
Not Equal To a != b
Equal To a == b
Logical Negation !a
Logical AND a && b
Logical OR a || b
Any operation can given a True or False value 0 is False Anything else is True
2 + 3; is True
0 / 1234; is False
Comparison operators return an integer (0 for False, 1 for True)
int i = !( 2 >= 5);
C++ Bitwise Operators
Operator Name Syntax
Bitwise Left Shift a << b
Assignment by Bitwise Left Shift a <<= b
Bitwise Right Shift a >> b
Assignment by Bitwise Right Shift a >>= b
Bitwise One's Complement ~a
Bitwise AND a & b
Assignment by Bitwise AND a &= b
Bitwise OR a | b
Assignment by Bitwise OR a |= b
Bitwise XOR a ^ b
Assignment by Bitwise XOR a ^= b
C++ Other OperatorsBasic Assignment a = b
Function, Call a()
Array Subscript a[b]
Indirection (Dereference) *a
Address-of (Reference) &a
Member by Pointer a->b
Member a.b
Member by Pointer Function Pointer Indirection a->*b
Member Function Pointer Indirection a.*b
Cast (type) a
Comma a , b
Ternary Conditional a ? b : c
Scope Resolution a::b
Member Function Pointer a::*b
Size-of sizeof asizeof(type)
Type Identification typeid(a)typeid(type)
Allocate Storage new type
Allocate Storage (Array) new type[n]
Deallocate Storage delete a
Deallocate Storage (Array) delete[] a
C++ Operators – try out some math
Math - addition (+), subtraction (-), multiplication (*), division (/), and
modulus (%). Code up this fragment in a new project and find the
answers.int n1 = 7;int n2 = 2;int ans1 = 0, ans2 = 0, ans3 = 0, ans4 = 0, ans5 = 0;
ans1 = n1 + n2;ans2 = n1 - n2;ans3 = n1 * n2;ans4 = n1 / n2;ans5 = n1 % n2;
C++ Program structure – For loop
for (int i = 0; i < MAX_NUMBER_OF_CATS + 1; i++)
{
listOfCats[i] = NULL;
}
C++ Program structure – While loop
while (cat_p != NULL)
{
delete cat_p;
cat_p = listOfCats[++postionInList];
}
C++ Program structure – Do loop
So what does this code fragment do?char ch = ‘a’; do {
cout << ch << ‘ ‘; ch++;
} while ( ch <= ‘z’ ); Now see what other characters are out there,
change the initial value of ch to 0 (not ‘0’) and the final value to 254 (not ‘254’). (Why did I pick that range?, try going over 254 and see what happens.)
C++ Program structure – If/else
if (sensor_inputs.raw_direction_cmd < 123) {if (Front_cal_needed) {
pwm06 = CALIBRATE_RIGHT_SPEED; CALIBRATE_FRONT_LED = LED_ON; /* signal calibrating the front
*/} else {
pwm05 = CALIBRATE_RIGHT_SPEED;CALIBRATE_BACK_LED = LED_ON; /* signal calibrating the back */
}} else if (sensor_inputs.raw_direction_cmd > 133) {
if (Front_cal_needed) {pwm06 = CALIBRATE_LEFT_SPEED; CALIBRATE_FRONT_LED = LED_ON; /* signal calibrating the front
*/} else { /* assume it is back */
pwm05 = CALIBRATE_LEFT_SPEED;CALIBRATE_BACK_LED = LED_ON; /* signal calibrating the back */
}}
C++ Program structure – switch
char* Pet::GetGenderAsString(){ char* genderString; switch (itsGender) { case Male: genderString = "Male"; break; case Female: genderString = "Female"; break; default: genderString = "???"; break; } // end gender switch return genderString;}
C++ Attributes (aka variables): Definition
All the variables that a program is going to use must be declared prior to useassociates a type and a name with the
variableallows the compiler to decide how much
storage space to allocate for storage of the value associated with the identifier and to assign an address
C++ Attributes: Scope
Attribute is only defined within the “block” of code that it was declared in.
Can re-use names in different blocks (advanced topic – namespaces)
Typically attributes are defined To be globally available in an include file used by everyone
(see static modifier) As part of a class or structure At the start of a method At the start of a code control block (e.g. for loop)
Scope operator is :: Cat::getAge();
Declaration is different than using “new”
C++ Attributes: Pointers/References
Every variable has an address. Even without knowing the specific address of a given variable, you can store that address in a pointer
Use naming convention foo_p So what does this do?
int myAge = 47;int* foo_p = 0;foo_p = &myAge;myAge++;cout << *foo_p;
Now try and increment the age using foo_p instead of myAge++.
C++ - Attributes: Built in types
int represent negative and positive integer values Typically stored in one word (16 bits), with a range of 32768
to +32767 char
a letter, a digit or a punctuation character Typically stored as a byte in memory (8 bits) with a range of 0
– 255. (Recall the do loop example.) bool
hold the values true (1) or false (0) Typically stored as a byte (8 bits) in memory
float any real numeric value Memory and accuracy depends on the system
C++ Attributes: Modifiers
Const – value can not be changed Static – only one instance created in memory Extern – defined in some other file Long – modifies integer to be two words Unsigned – modifies integer to be only positive Double – modifies float to have twice the
range
C++ Attributes: User defined types - typedef
You can create types
Typedef char* String_p;
-- somewhere later ---
String_p myName_p = 0;
C++ Attributes: User defined types - Arrays
collection of data storage locations, each of which holds the same type of data
Keyword are the square brackets, []int ages[6]int IntegerArray[] = { 10, 20, 30, 40, 50 }; int theArray[5][3]Cat* listOfCats[10] (this is a BAD name – why?) How many fence posts you need for a 10-foot
fence if you need one post for every foot?
C++ Attributes: User defined types - Structures
structure is just a collection of variables
typedef struct {
int age;
char name[80];
bool cool;
} personAttributes;
C++ Attributes: User defined types - Classes
class is a special structure - just a collection of variables - PLUS a set of related functions
class Cat : public Pet{
unsigned int itsAge; unsigned int itsWeight; Meow();
};
C++ Attributes: User defined types – Classes data hiding
Private – only this class can get at it Protected – only this class and inheriting
classes can get at it Public – everyone has access
class Cat : public Pet{ Private:
unsigned int itsAge; unsigned int itsWeight;
Protected:int getWeight();
Public:Meow(); int getAge();
};
C++ Attributes: User defined types – Classes - Inheritance
Define classes that derive from one another such that one is a specialization of the other.
A cat is a pet is a mammal is a animal The derived class can modify the attributes
and methods of the base class The base class can leave things undefined
using the virtual key word, meaning that the derived class MUST define it.
Now add a fish to the collection of pets