Sei sulla pagina 1di 20

NAME: Siongco, Uriel S.

COURSE AND SECTION: ECE-1 A12

LABORATORY DRILL NO. 6


CREATING CLASSES WITH FRIENDS AND OVERLOADING
OPERATORS

Objectives:
- Create classes
- Learn about encapsulating class components
- Implement functions in a class
- Understand the unusual use of private functions and public data
- Consider scope when defining member functions
- Use static class members
- Learn about the this pointer
- Understand the advantages of polymorphism
- Classify the roles of member functions
- Understand constructors
- Write constructors both with and without parameters
- Overload constructors
- Create destructors
- Understand composition
- Learn how, why, and when to use the preprocessor directives #ifndef, #define, and
#endif
- Master techniques for improving classes
- Learn what a friend is
- Declare a friend function
- Examine the benefits of polymorphism and overloading
- Use a friend function to access data from two classes
- Learn the general rules that apply to operator overloading
- Overload an arithmetic operator
- Overload operators to work with an object and a primitive type
- Chain multiple mathematical operations in an expression
- Overload the insertion operator (<<) for output
- Overload the extraction operator (>>) for input
- Overload the prefix and postfix ++ and -- operators
- Overload the == operator
- Overload the = operator
- Overload the subscript and parenthesis operators

Discussion:
- Using Classes
- Class Features and Design Issues
- Understanding Friends and Overloading Operators

Programming Exercise 10-7:


Design and implement a class dayType that implements the day of the week in a program.
The class dayType should store the day, such as Sun for Sunday. The program should be
able to perform the following operations on an object of type dayType:

1. Set the day.


2. Print the day.
3. Return the day.
4. Return the next day.
5. Return the previous day.
6. Calculate and return the day by adding certain days to the current day. For example,
if the current day is Monday and we add 4 days, the day to be returned is Friday.
Similarly, if today is Tuesday and we add 13 days, the day to be returned is Monday.
7. Add the appropriate constructors.

Note: For your final output, enter “Sun” and 35 days and you should have an
output similar to below.

Source Code and Output:


#include"pch.h"
#include<conio.h>
#include<iostream>
#include<string>

using namespace std;

class dayType
{
private:
static const int Size = 7;
string WeekArray[Size] = { "Mon", "Tue", "Wed", "Thur", "Fri", "Sat", "Sun" };
string Day;
int IndexValue;
public:
dayType(string);
void Get_Before_After();
void Get_Forecasted_Day(int);
string Get_Day();
};
dayType::dayType(string ThisDay)
{
Day = ThisDay;

int i = 0;

while (WeekArray[i] != Day)


{
i++;
}

IndexValue = i;
}

void dayType::Get_Before_After()
{
if (IndexValue == 0)
{
cout << "\nDay prior: " << WeekArray[6];
cout << "\nDay following: " << WeekArray[IndexValue + 1];
}
else if (IndexValue == 6)
{
cout << "\nDay prior: " << WeekArray[IndexValue - 1];
cout << "\nDay following: " << WeekArray[0];
}
else
{
cout << "\nDay prior: " << WeekArray[IndexValue - 1];
cout << "\nDay following: " << WeekArray[IndexValue + 1];
}
}

void dayType::Get_Forecasted_Day(int NumDays)


{
int i = IndexValue;
while (NumDays != 0)
{

if (i == 6)
{
i = 0;
}
else
{
i++;
}
NumDays--;
}

cout << "\nForecasted day: " << WeekArray[i];


}

string dayType::Get_Day()
{
return Day;
}
int main()
{
string DayEntered;
int NumDays;

cout << "\nChoose one of the following: Mon, Tue, Wed, Thur, Fri, Sat, Sun";
cout << "\nSet the day to be stored: ";
getline(cin, DayEntered);

dayType ThisDay(DayEntered);

cout << endl << "The day has been set to: " << ThisDay.Get_Day() << endl;

ThisDay.Get_Before_After();

cout << "\n\nEnter the number of days to forecast the next day: ";
cin >> NumDays;

ThisDay.Get_Forecasted_Day(NumDays);

cout << endl;


_getch();
return 0;
}

Programming Exercise 10-17:

(Tic-Tac-Toe) | Write a program that allows two players to play the tic-tac-toe game. Your
program must contain the class ticTacToe to implement a ticTacToe object. Include a 3-by-3
two-dimensional array, as a private member variable, to create the board. If needed, include
additional member variables. Some of the operations on a ticTacToe object are printing the
current board, getting a move, checking if a move is valid, and determining the winner after
each move. Add additional operations as needed.

Write a main that runs your game.

Note: For your final output, take a screenshot of Player X winning and another of
Player O winning.

Source Code and Output:


#include"pch.h"
#include<iostream>
#include<conio.h>
#include<string>

using namespace std;

class ticTacToe
{
private:
static const int Size = 3;
string ticTacToeBoard[Size][Size] = { {" ", " ", " "},
{" ", " ", " "},
{" ", " ", " "}
};
int Winner = 0;
public:
void Display_Board();
bool Plot_Move(int &, int &, string &);
void Test_Winner();
int Is_Winner();
};

void ticTacToe::Display_Board()
{
cout << "\nTic-Tac-Toe C++ Game" << endl;

cout << "\n 1 2 3" << endl;

for (int row = 0; row <= 2; row++)


{
cout << " " << row + 1 << " ";

for (int col = 0; col <= 2; col++)


{
cout << "|"<<ticTacToeBoard[row][col] << "|";

if (col == 2)
{
cout << endl;
}
}
}
}

bool ticTacToe::Plot_Move(int &Row, int &Col, string &Marker)


{
bool Move_Successful;

if (ticTacToeBoard[Row - 1][Col - 1] != " ")


{
cout << "\nInvalid move. Please try again.";
Move_Successful = false;
_getch();
}
else
{
ticTacToeBoard[Row - 1][Col - 1] = Marker;
Move_Successful = true;
}

return Move_Successful;
}

void ticTacToe::Test_Winner()
{
if (ticTacToeBoard[0][0] == "X" && ticTacToeBoard[0][1] == "X" &&
ticTacToeBoard[0][2] == "X")
{
cout << "\nPlayer X Wins!" << endl;
_getch();
Winner = 1;
}
else if (ticTacToeBoard[1][0] == "X" && ticTacToeBoard[1][1] == "X" &&
ticTacToeBoard[1][2] == "X")
{
cout << "\nPlayer X Wins!" << endl;
_getch();
Winner = 1;
}
else if (ticTacToeBoard[2][0] == "X" && ticTacToeBoard[2][1] == "X" &&
ticTacToeBoard[2][2] == "X")
{
cout << "\nPlayer X Wins!" << endl;
_getch();
Winner = 1;
}
else if (ticTacToeBoard[0][0] == "O" && ticTacToeBoard[0][1] == "O" &&
ticTacToeBoard[0][2] == "O")
{
cout << "\nPlayer O Wins!" << endl;
_getch();
Winner = 1;
}
else if (ticTacToeBoard[1][0] == "O" && ticTacToeBoard[1][1] == "O" &&
ticTacToeBoard[1][2] == "O")
{
cout << "\nPlayer O Wins!" << endl;
_getch();
Winner = 1;
}
else if (ticTacToeBoard[2][0] == "O" && ticTacToeBoard[2][1] == "O" &&
ticTacToeBoard[2][2] == "O")
{
cout << "\nPlayer O Wins!" << endl;
_getch();
Winner = 1;
}
else if (ticTacToeBoard[0][0] == "X" && ticTacToeBoard[1][0] == "X" &&
ticTacToeBoard[2][0] == "X")
{
cout << "\nPlayer X Wins!" << endl;
_getch();
Winner = 1;
}
else if (ticTacToeBoard[0][1] == "X" && ticTacToeBoard[1][1] == "X" &&
ticTacToeBoard[2][1] == "X")
{
cout << "\nPlayer X Wins!" << endl;
_getch();
Winner = 1;
}
else if (ticTacToeBoard[0][2] == "X" && ticTacToeBoard[1][2] == "X" &&
ticTacToeBoard[2][2] == "X")
{
cout << "\nPlayer X Wins!" << endl;
_getch();
Winner = 1;
}
else if (ticTacToeBoard[0][0] == "O" && ticTacToeBoard[1][0] == "O" &&
ticTacToeBoard[2][0] == "O")
{
cout << "\nPlayer O Wins!" << endl;
_getch();
Winner = 1;
}
else if (ticTacToeBoard[0][1] == "O" && ticTacToeBoard[1][1] == "O" &&
ticTacToeBoard[2][1] == "O")
{
cout << "\nPlayer O Wins!" << endl;
_getch();
Winner = 1;
}
else if (ticTacToeBoard[0][2] == "O" && ticTacToeBoard[1][2] == "O" &&
ticTacToeBoard[2][2] == "O")
{
cout << "\nPlayer O Wins!" << endl;
_getch();
Winner = 1;
}
else if (ticTacToeBoard[0][0] == "X" && ticTacToeBoard[1][1] == "X" &&
ticTacToeBoard[2][2] == "X")
{
cout << "\nPlayer X Wins!" << endl;
_getch();
Winner = 1;
}
else if (ticTacToeBoard[2][0] == "X" && ticTacToeBoard[1][1] == "X" &&
ticTacToeBoard[0][2] == "X")
{
cout << "\nPlayer X Wins!" << endl;
_getch();
Winner = 1;
}
else if (ticTacToeBoard[0][0] == "O" && ticTacToeBoard[1][1] == "O" &&
ticTacToeBoard[2][2] == "O")
{
cout << "\nPlayer O Wins!" << endl;
_getch();
Winner = 1;
}
else if (ticTacToeBoard[2][0] == "O" && ticTacToeBoard[1][1] == "O" &&
ticTacToeBoard[0][2] == "O")
{
cout << "\nPlayer O Wins!" << endl;
_getch();
Winner = 1;
}
else
{
Winner = 0;
}
}

int ticTacToe::Is_Winner()
{
return Winner;
}

int main()
{
ticTacToe Game;
int Row, Col, Win = 0;
bool Move_Successful;
string Marker;

Repeat1:
system("cls");
Game.Display_Board();

Game.Test_Winner();
Win = Game.Is_Winner();

if (Win == 1)
return 0;

cout << "\nPlayer X - Make your move: ";


cin >> Row >> Col;
Marker = "X";
Move_Successful = Game.Plot_Move(Row, Col, Marker);
if (Move_Successful == false)
{
goto Repeat1;
}
Repeat2:
system("cls");
Game.Display_Board();

Game.Test_Winner();
Win = Game.Is_Winner();
if (Win == 1)
return 0;

cout << "\nPlayer O - Make your move: ";


cin >> Row >> Col;
Marker = "O";
Move_Successful = Game.Plot_Move(Row, Col, Marker);
if (Move_Successful == false)
{
goto Repeat2;
}

goto Repeat1;

_getch();
return 0;
}
Programming Exercise 10-13:

In this exercise, you will design a class memberType.


1. Each object of memberType can hold the name of a person, member ID, number of
books bought, and amount spent.
2. Include the member functions to perform the various operations on the objects of
memberType - for example, modify, set, and show a person’s name. Similarly, up-
date, modify, and show the number of books bought and the amount spent.
3. Add the appropriate constructors.
4. Write the definitions of the member functions of
memberType.
5. Write a program to test various operations of your class
memberType.

Note: For your final output, feed the details as


shown on the image to each object and have the
class memberType display all three object records.

Source Code and Output:


#include"pch.h"
#include<iostream>
#include<string>
#include<conio.h>

using namespace std;

class memberType
{
private:
string Member_Name, Member_ID;
int Books_Bought;
double Total_Spent;
public:
memberType(string, string, int, double);
void Setup_Records(string, string, int, double);
void Show_Records();
};

memberType::memberType(string PassName, string PassID, int PassBooksBought, double


PassTotalSpent)
{
Member_Name = PassName;
Member_ID = PassID;
Books_Bought = PassBooksBought;
Total_Spent = PassTotalSpent;
}

void memberType::Setup_Records(string PassName, string PassID, int PassBooksBought,


double PassTotalSpent)
{
Member_Name = PassName;
Member_ID = PassID;
Books_Bought = PassBooksBought;
Total_Spent = PassTotalSpent;
}

void memberType::Show_Records()
{
cout << endl << "Customer's Name: " << Member_Name;
cout << endl << "Member ID: " << Member_ID;
cout << endl << "Books bought: " << Books_Bought;
cout << endl << "Total: $" << Total_Spent;
}

int main()
{
string GetName, GetID;
int GetBooksBought, Option;
double GetTotalSpent;
memberType Member_One("", "", 0, 0.00);
memberType Member_Two("", "", 0, 0.00);
memberType Member_Three("", "", 0, 0.00);

MainMenu:
system("cls");

cout << "\nBook Purchase" << endl;


cout << "\nMenu" << endl;
cout << "[1] Setup record..." << endl
<< "[2] Show records..." << endl
<< "[3] Update records..." << endl
<< "[4] Exit..." << endl
<< "Option: ";
cin >> Option;

switch (Option)
{
case 1:
system("cls");

cout << "\nName of customer [1]: ";


cin.ignore();
getline(cin, GetName);
cout << "Member ID: ";
//cin.ignore();
getline(cin, GetID);
cout << "Number of books purchased: ";
cin >> GetBooksBought;
cout << "Total: $";
cin >> GetTotalSpent;

Member_One.Setup_Records(GetName, GetID, GetBooksBought, GetTotalSpent);

cout << "\nName of customer [2]: ";


cin.ignore();
getline(cin, GetName);
cout << "Member ID: ";
//cin.ignore();
getline(cin, GetID);
cout << "Number of books purchased: ";
cin >> GetBooksBought;
cout << "Total: $";
cin >> GetTotalSpent;

Member_Two.Setup_Records(GetName, GetID, GetBooksBought, GetTotalSpent);

cout << "\nName of customer [3]: ";


cin.ignore();
getline(cin, GetName);
cout << "Member ID: ";
//cin.ignore();
getline(cin, GetID);
cout << "Number of books purchased: ";
cin >> GetBooksBought;
cout << "Total: $";
cin >> GetTotalSpent;

Member_Three.Setup_Records(GetName, GetID, GetBooksBought,


GetTotalSpent);

goto MainMenu;
case 2:
system("cls");

cout << "\nRecord No. 1" << endl;


Member_One.Show_Records();
cout << endl;
cout << "\nRecord No. 2" << endl;
Member_Two.Show_Records();
cout << endl;
cout << "\nRecord No. 3" << endl;
Member_Three.Show_Records();

_getch();
goto MainMenu;;
case 3:
SubMenu:
system("cls");

int RecNum;

cout << "\nEnter record number to update (1, 2, 3, or 0 to go back): ";


cin >> RecNum;

switch (RecNum)
{
case 1:
system("cls");

cout << "\nName of customer [1]: ";


cin.ignore();
getline(cin, GetName);
cout << "Member ID: ";
//cin.ignore();
getline(cin, GetID);
cout << "Number of books purchase: ";
cin >> GetBooksBought;
cout << "Total: $";
cin >> GetTotalSpent;

Member_One.Setup_Records(GetName, GetID, GetBooksBought,


GetTotalSpent);

goto MainMenu;
case 2:
system("cls");

cout << "\nName of customer [2]: ";


cin.ignore();
getline(cin, GetName);
cout << "Member ID: ";
//cin.ignore();
getline(cin, GetID);
cout << "Number of books purchase: ";
cin >> GetBooksBought;
cout << "Total: $";
cin >> GetTotalSpent;

Member_Two.Setup_Records(GetName, GetID, GetBooksBought,


GetTotalSpent);

goto MainMenu;
case 3:
system("cls");

cout << "\nName of customer [3]: ";


cin.ignore();
getline(cin, GetName);
cout << "Member ID: ";
//cin.ignore();
getline(cin, GetID);
cout << "Number of books purchase: ";
cin >> GetBooksBought;
cout << "Total: $";
cin >> GetTotalSpent;

Member_Three.Setup_Records(GetName, GetID, GetBooksBought,


GetTotalSpent);

goto MainMenu;
default:
cout << "\nInvalid option. Please try again!";
_getch();
goto SubMenu;
case 0:
goto MainMenu;
}
case 4:
return 0;
default:
cout << "\nInvalid option. Please try again";
_getch();
goto MainMenu;
}

_getch();
return 0;
}
Programming Exercise 10-23:

Programming Exercise 22 prompted the user to input the number of times the dice were to
be rolled and the desired sum, and the program output the number of times the desired sum
occurred.

Modify Programming Exercise 22 as follows: Suppose you roll 4 dice 1000 times. Store the
sum of the numbers rolled in each roll into an array and then use this array to print a bar
graph similar to the bar graph in Programming Example Data Comparison (Chapter 6) at the
end of the program.

Test run your program using 4, 5, and 6 dice and the number of rolls 2500, 3000, and 5000.
Run this numbers multiple times and observe the outputs. What type of curve does the shape
of your bar graph resemble?

Source Code and Output:


#include"pch.h"
#include<iostream>
#include<iomanip>
#include<stdio.h>
#include<conio.h>
#include"die.h"

using namespace std;

int main()
{
int Number_of_Dice, Number_of_Rolls, Sum_of_Numbers = 0;
void Print_Graph(int[], int, int);

cout << "\nEnter the number of dice to be rolled: ";


cin >> Number_of_Dice;

cout << "\nHow many times should the dice be rolled? ";
cin >> Number_of_Rolls;

die *Dice_Array = new die[Number_of_Dice];


int *Total_Per_Roll = new int[Number_of_Rolls];

for (int i = 0; i < Number_of_Rolls; i++)


{
Sum_of_Numbers = 0;

for (int j = 0; j < Number_of_Dice; j++)


{
Dice_Array[j].roll();
Sum_of_Numbers = Sum_of_Numbers + Dice_Array[j].getNum();
}
Total_Per_Roll[i] = Sum_of_Numbers;
}

Print_Graph(Total_Per_Roll, Number_of_Rolls,Number_of_Dice);

delete[] Dice_Array;
delete[] Total_Per_Roll;

return 0;
}

void Print_Graph(int Total_Per_Roll[], int Number_of_Rolls, int Number_of_Dice)


{
int Total1Dot, Total6Dots;

Total1Dot = 1 * Number_of_Dice;
Total6Dots = 6 * Number_of_Dice;

for (int i = Total1Dot; i <= Total6Dots; i++)


{
cout << endl << i << ": ";

for (int j = 0; j < Number_of_Rolls; j++)


{
if (Total_Per_Roll[j] == i)
{
cout << "*";
}
}
}
cout << endl;
}

#include<cstdlib>
#include<ctime>

class die
{
private:
int num;
public:
die();
//Default constructor
//Sets the default number rolled by a die to 1

void roll();
//Function to roll a die.
//This function uses a random number generator to randomly
//generate a number between 1 and 6, and stores the number
//in the instance variable num.

int getNum() const;


//Function to return the number on the top face of the die.
//Returns the value of the instance variable num.
};

die::die()
{
num = 1;
srand(time(0));
}

void die::roll()
{
num = rand() % 6 + 1;
}

int die::getNum() const


{
return num;
}
The graphs take the shape of a bell curve indicating that the dice will most likely land with
their face value between 1 and 6.

Question #1:

In this chapter, you learned that instance data and methods belong to objects (which are
class members), but that static data and methods belong to a class as a whole. Consider
the real-life class named StateInTheUnitedStates. Name some real-life attributes of
this class that are static attributes and instance attributes. Create another example of a
real-life class and discuss what its static and instance members might be.

Your answer: Examples of instance attributes are 401-K, social security, and race. Examples
of static attributes, are nationality, democrat, and republic.

Another example of a real-life class is the military. The ranks and years of service are good
examples of instance attributes. For static attribute, a good example would be the branch the
object is assigned to.

Question #2:

What are the advantages of declaring named constants in your classes and programs?
Can you think of any disadvantages?

Your answer:One advantage of declaring constants is that the declared value would retain
itself for all throughout the program, avoiding unnecessary repetition of declaring a variable
for the value. An example of a disadvantage would be when the size of the array is defined
by the user. A constant will no longer apply, therefore, the programmer will have to take a
different approach to declare an array of variable size.
Question #3:

What does the term syntactic sugar mean? From your knowledge of the C++ programming
language, list as many syntactic sugar features as you can.

Your answer: Syntactic sugar is syntax that allows a programming language easier to read
or to express, making it sweeter for human use. Examples of syntactic sugar are arrays,
encapsulation, classes, and functions.

Potrebbero piacerti anche