Write a class Heading that can be used to store one of the principal compass dir
ID: 3667154 • Letter: W
Question
Write a class Heading that can be used to store one of the principal compass directions, 'N', 'E', 'S', 'W'. It will have the following methods. Constructor-builds a Heading as one of 'N', 'E', 'S', 'W', defaults to 'N'. You do NOT need to do any data validation (i.e., don't need to check the inputs or raise exceptions.) getretrive the Heading as a string. _repr_ -see output. right - changes the heading by turning right but 90 degrees, i.e., 'N' right arrow 'E' right arrow 'S' right arrow 'W' right arrow 'N' left - changes the heading by turning left by 90, i.e., the reverse of the above Constructor using an argument, repr, get, right left. Constructor called without an argument.Explanation / Answer
#include <iostream>
using namespace std;
class Heading
{
private:
char myHeading; //Private member to store head value
public:
// parameterized constructor
Heading(char heading)
{
cout << "You are moving towards - " << heading << endl;
myHeading = heading;
}
// Default constructor
Heading()
{
cout << "You are moving towards - N" << endl;
myHeading = 'N';
}
// method gets Heading value
void getHeading( )
{
cout << "h.get() - '" << myHeading << "'" << endl;
}
// used for seeing output
void showHeadingDirection( )
{
cout << "Currently Heading('" << myHeading << "')" << endl << endl;
}
// used for turning right by 90 degree
void turnRight( )
{
switch(myHeading){
case 'N' :
myHeading = 'E'; break;
case 'E' :
myHeading = 'S'; break;
case 'S' :
myHeading = 'W'; break;
case 'W' :
myHeading = 'N'; break;
}
}
// used for turning left by 90 degree
void turnLeft( )
{
switch(myHeading){
case 'N' :
myHeading = 'W'; break;
case 'E' :
myHeading = 'N'; break;
case 'S' :
myHeading = 'E'; break;
case 'W' :
myHeading = 'S'; break;
}
}
};
// Main function for the program
int main( )
{
cout << " h = Heading('E')";
Heading heading('E');
heading.showHeadingDirection();
heading.getHeading();
cout << "heading.turnRight()" << endl;
heading.turnRight();
heading.showHeadingDirection();
cout << "heading.turnRight()" << endl;
heading.turnRight();
heading.showHeadingDirection();
cout << "heading.turnRight()" << endl;
heading.turnRight();
heading.showHeadingDirection();
cout << "heading.turnLeft()" << endl;
heading.turnLeft();
heading.showHeadingDirection();
cout << " with out parameter in constrcor - " << endl;
cout << "head = Heading()" << endl;
Heading head;
head.showHeadingDirection();
cout << "head.turnLeft()" << endl;
head.turnLeft();
heading.showHeadingDirection();
cout << "head.turnRight()" << endl;
head.turnRight();
head.showHeadingDirection();
cout << "head.turnRight()" << endl;
head.turnRight();
head.showHeadingDirection();
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.