Friend function strange behaviour - c++

I'm learning C++ by myself and one of the programs that I made is sort of a school information system, it is not my first OOP program but this time I experience some strange behavior of a friend function.
I have a derived class Student which has a private member - static array of Courses objects, and finally the main container class Class which has a member - dynamic array of Students objects.
as you can see avg member of student is calculated using a friend function of Courses class (calc_avg receives an array of Courses sums it's grades and divides by course number), it works like a charm.
The problem starts once I try to calculate an average grade (class_avg) for a Class object - I use the same logic - create a friend function of Student (class_avarage that will have access to each students avg) that will receive an array of Student objects and it's size, add each students average grade and divide by array size - for some reason it receives and returns garbage values, I've been trying to fix it for 3 hours and I cant find the problem, help me if you can - here is the relevant code (independent derived classes are not included and output functions are minimized):
main //only container object creation and IO functions (all .h files included)
Class test1;
test1.input_class();
test1.output_class();
Student.h
#include "Person.h"
#include "Courses.h"
#ifndef STUDENT_H
#define STUDENT_H
class Student : public Person
{
public:
Student();
void input_student ();
void output_student ();
friend float class_avarage (Student* array, int);
~Student();
protected:
private:
Courses my_courses [6];
float avg;
};
#endif // STUDENT_H
Student.cpp
#include "Student.h"
Student::Student()
{
//ctor
}
void Student::input_student ()
{
cout << "Please enter students info:" << endl;
input_info();
my_courses[0].input_grades ("Math");
my_courses[1].input_grades ("English");
my_courses[2].input_grades ("Science");
my_courses[3].input_grades ("History");
my_courses[4].input_grades ("Art");
my_courses[5].input_grades ("Sports");
}
void Student::output_student ()
{
int i;
cout << "Students info:" << endl;
output_info();
cout << " Course Grade" << endl;
for (i = 0; i < 6; i++)
{
my_courses[i].output_grades ();
}
avg = calc_avg(my_courses, 6);
cout << " " << "Average grade for student: " << avg << endl;
}
Student::~Student()
{
//dtor
}
float calc_avg (Courses* array, int size)
{
int i;
float sum = 0;
for (i = 0; i < size; i++)
{
sum += array[i].grade;
}
return sum/size;
}
Courses.h
#include <iostream>
#include <iomanip>
#include <string>
#ifndef COURSES_H
#define COURSES_H
using std::cout;
using std::cin;
using std::endl;
using std::string;
class Courses
{
public:
Courses();
void input_grades(string);
void output_grades();
friend float calc_avg (Courses*, int);
~Courses();
protected:
private:
string course_name;
int grade;
};
#endif // COURSES_H
Courses.cpp
#include "Courses.h"
Courses::Courses() : course_name ("Default"), grade (-1)
{
//ctor
}
void Courses::input_grades (string temp_name)
{
course_name = temp_name;
cout << "Enter " << temp_name << " grade: ";
cin >> grade;
cin.get();
}
void Courses::output_grades ()
{
cout << " " << course_name << ": " << grade << endl;
}
Courses::~Courses()
{
//dtor
}
Class.h
#include <iostream>
#include <string>
#include "Teacher.h"
#include "Student.h"
#ifndef CLASS_H
#define CLASS_H
using std::cout;
using std::cin;
using std::endl;
using std::string;
class Class
{
public:
Class();
void input_class ();
void output_class ();
~Class();
protected:
private:
string class_name;
Teacher class_teacher;
Student* pupils;
int students_number;
float class_avg;
};
#endif // CLASS_H
Class.cpp
#include "Class.h"
Class::Class() : class_name ("A"), pupils (NULL), students_number (0), class_avg (0)
{
//ctor
}
void Class::input_class ()
{
int i;
//input class data
cin >> students_number;
cin.get();
pupils = new (std::nothrow) Student [students_number];
if (!pupils)
{
cout << "Allocation failed!" << endl;
}
else
{
for (i = 0; i < students_number; i++)
{
pupils[i].input_student();
}
}
class_avg = class_avarage (pupils, students_number);
}
void Class::output_class ()
{
int i;
cout << " Displaying info of class :" << class_name << endl <<
" Class average grade: " << class_avg << endl;
class_teacher.output_teacher();
cout << " Number of students: " << students_number << endl << " Students: " << endl;
for (i = 0; i < students_number; i++)
{
pupils[i].output_student();
}
}
Class::~Class()
{
//dtor
}
float class_avarage (Student* array, int size)
{
cout << size << endl;
int i;
float total = 0;
for (i = 0; i < size; i++)
{
total += array[i].avg;
}
return total/size;
}

Why should anyone want to use friend functions? Just add simple getter for Cource.grade member and lasy getter for Student.avg. This will eliminate the possibility to get garbage instead of data.
Also, use std::vector and pass them throught std::vector&, not arrays and pointers.

Related

Why the function doesn't recognize an object created in main()?

I have to make a Shopping Cart program for school, and there are more moving parts in this program than I've ever had to deal with. I'm trying to figure out why the function in my main.cpp can't recognize the object that I created in main(). It keeps saying that
the cart is not declared in the scope.
I still have to finish building out the menu, but I can't even get it to recognize the object that gets created in main.
I can see that the object is being properly created, because it can be manipulated within the main() no problem. Furthermore, I even have a few placeholder commands in there to get it working. The thing is that the homework assignment requires the menu to be in a function.
#include <iostream>
#include <string>
#include "ItemToPurchase.h"
#include "ShoppingCart.h"
using namespace std;
void PrintMenu()
{
while (true)
{
string choice;
cout << "MENU" << endl;
cout << "a - Add item to cart" << endl;
cout << "d - Remove item from cart" << endl;
cout << "c - Change item quantity" << endl;
cout << "i - Output item's descriptions" << endl;
cout << "o - Output shopping cart" << endl;
cout << "q - Quit" << endl;
cout << endl;
cout << "Choose an option: " << endl;
cin >> choice;
if (choice == "a") {
cart.GetDate();
}
else if (choice == "d") {
}
else if (choice == "c") {
}
else if (choice == "i") {
}
else if (choice == "o") {
}
else if (choice == "q") {
break;
}
else {
cout << "That is not a valid choice" << endl;
}
}
}
int main()
{
string name;
string date;
cout << "Enter customer's name: " << endl;
cin >> name;
cout << "Enter today's date: " << endl;
cin >> date;
cout << endl;
cout << "Customer name: " << name << endl;
cout << "Today's date: " << date << endl;
ShoppingCart cart(name, date);
ItemToPurchase apple("apple", 1, 4, "apple");
cout << cart.GetDate();
cart.AddItem(apple);
cout << cart.GetNumItemsInCart();
PrintMenu();
}
#ifndef SHOPPINGCART_H
#define SHOPPINGCART_H
#include <string>
#include <iostream>
#include <vector>
#include "ItemToPurchase.h"
using namespace std;
class ShoppingCart
{
private:
string customerName = "none";
string currentDate = "January 1, 2016";
vector<ItemToPurchase> cartItems;
public:
ShoppingCart(string name, string date);
string GetCustomerName() const;
string GetDate();
void AddItem(ItemToPurchase);
void RemoveItem(string);
void ModifyItem();
int GetNumItemsInCart();
double GetCostofCart();
void PrintTotal();
string PrintDecriptions();
};
#endif
#include <iostream>
#include <string>
#include <vector>
#include "ShoppingCart.h"
using namespace std;
ShoppingCart::ShoppingCart (string name, string date){
customerName=name;
currentDate= date;
}
string ShoppingCart::GetCustomerName() const
{
return customerName;
}
string ShoppingCart::GetDate()
{
return currentDate;
}
void ShoppingCart::AddItem(ItemToPurchase item)
{
cartItems.push_back(item);
}
void ShoppingCart::RemoveItem(string name)
{
for (int i = 0; i < cartItems.size(); i++)
{
if (cartItems.at(i).GetName() == name)
{
cartItems.erase(cartItems.begin() + i);
}
else
{
cout << "Item not found in cart. Nothing removed." << endl;
}
}
}
int ShoppingCart::GetNumItemsInCart(){
int number;
number = cartItems.size();
return number;
}
double ShoppingCart::GetCostofCart()
{
double sum = 0.0;
for (int i = 0; i < cartItems.size(); i++)
{
sum += cartItems[i].GetQuantity() * cartItems[i].GetPrice();
}
return sum;
}
#include "ItemToPurchase.h"
void ItemToPurchase::SetName(string SetItemName){
itemName = SetItemName;
}
void ItemToPurchase::SetPrice(int SetItemPrice){
itemPrice = SetItemPrice;
}
void ItemToPurchase::SetQuantity(int SetItemQuantity){
itemQuantity = SetItemQuantity;
}
string ItemToPurchase::GetName() const {
return itemName;
}
int ItemToPurchase::GetPrice() const {
return itemPrice;
}
int ItemToPurchase::GetQuantity() const {
return itemQuantity;
}
#include <string>
#include <iostream>
#ifndef ITEMTOPURCHASE_H
#define ITEMTOPURCHASE_H
using namespace std;
class ItemToPurchase
{
public:
ItemToPurchase(string a, int b, int c, string d)
{itemName = a;
itemPrice = b;
itemQuantity = c;
itemDescription =d;
}
void SetName(string SetItemName);
void SetPrice(int SetItemPrice);
void PrintItemDescription();
void SetQuantity(int SetItemQuantity);
string GetName() const;
int GetPrice() const;
int GetQuantity() const;
void SetDescription() const;
string GetDiscription() const;
void PrintItemCost() const;
private:
string itemName;
int itemPrice;
int itemQuantity;
string itemDescription;
};
#endif
[...], but I can't even get it, to recognize the object that gets created in main().
The main() and the PrintMenu() are two different functions with different scope. One can not know the variables from other, unless you pass or make known by any means.
In your case, you can pass the ShoppingCart object (i.e cart) from main() to the PrintMenu function, so that inside it will know which cart you meant for:
void PrintMenu(ShoppingCart& cart)
// ^^^^^^^^^^^^^^^^^^^^
{
// ...
}
and call the function from main() with the ShoppingCart object.
PrintMenu(cart);
That being said;
Please do not practice with using namespace std;. Read more: Why is "using namespace std;" considered bad practice?
If the member function does not modify the member, you should mark the function as const. Applies for all the getters of both ItemToPurchase and ShoppingCart classes.
When you return a non-trivial copyable objects like std::string in a getter, you should be avoiding copying. That means you might want to have changes like as below for all your getters which returns std::string:
const std::string& GetDate() const /* noexcept */
{
return currentDate;
}
This line in PrintMenu is the problem:
cart.GetDate();
The compiler looks for something called cart within the scope of that function, which does not exist. Once way to resolve this, is to pass a reference to the cart created in main to the PrintMenu function:
void PrintMenu(ShoppingCart &cart){
and call the function like this:
PrintMenu(cart);
Note that because, in the future, you'll want to modify cart in the menu, you'll need to pass it as a reference (i.e. with &) and not as a copy or constant reference.

Trying to pass an array of pointers to objects, to a function of another class in C++ (not allowed to use vectors)

I have a class named Student. I create many student objects in my main (each object representing one student.)What i'm really trying to do is pass each one of these students to function enter of School class, representing that a student enters the school and then print his/her name etc.Here's the code:
my study.h file consists of:
#include <iostream>
#include <cstring>
using namespace std;
class Student
{
private:
string name;
int no_floor;
int no_classroom;
public:
Student(const string& nam,int no_fl,int no_cla)//constructor
: name(nam), no_floor(no_fl), no_classroom(no_cla)
{
cout << "A new student has been created! with name " << name << " heading to floor: "<< no_floor << " class: " << no_classroom << endl;
};
~Student() //destructor
{
cout << "A Student to be destroyed! with name " << name << " is at floor: " << no_floor << " class: " << no_classroom;
};
Then the School class:
class School
{
private:
Student* pointer_array[2];
public:
School()//constructor
{
cout << "A New School has been created!" << endl;
};
~School(){//destructor
cout << "A School to be destroyed!" << endl;
};
void enter(Student student, int stc=0/*student counter*/);
};
on my main.cpp file: (memory allocation for each student)
#include <iostream>
#include <cstring>
#include <study.h>
using namespace std;
int main(void)
{
//Student creation
int i,floor,classroom;
string stname;
Student* students[2];
for(i=0; i<2; i++)
{
cin >> stname;
cin >> floor;
cin >> classroom;
students[i] = new Student(stname, floor, classroom);
}
School sch;
for(i=0; i<2; i++)
{
sch.enter(*(students[i]),i);
}
for(i=0; i<2; i++)
{
delete students[i];
}
}
Lastly on my study.cpp file i've got the School class function where i'm trying to pass each object by reference and not by coping them to a new object:
#include <iostream>
#include <cstring>
#include <study.h>
using namespace std;
void School::enter(Student student, int stc/*student counter*/)
{
pointer_array[stc] = &student;
cout << "pointer array[" << stc << "]:" << pointer_array[stc] << endl;
//^ this cout prints the same adress for both students array[0]:0x1ffefffd20
// array[1]:0x1ffefffd20
}
Any ideas on how to pass pointers to all students and not just one. Again i'm trying to pass the array by reference.Thoughts?
here's the solution to this problem
School class:
class School
{
private:
Student* pointer_array[5];
public:
School()//constructor
{
cout << "A New School has been created!" << endl;
};
~School(){//destructor
cout << "A School to be destroyed!" << endl;
};
void enter(Student* student, int stc=0/*student counter*/);
};
Student class doesn't change:
class Student
{
private:
string name;
int no_floor;
int no_classroom;
public:
Student(const string& nam,int no_fl,int no_cla)//constructor
: name(nam), no_floor(no_fl), no_classroom(no_cla)
{
cout << "A new student has been created! with name " << name << " heading to floor: "<< no_floor << " class: " << no_classroom << endl;
};
~Student() //destructor
{
cout << "A Student to be destroyed! with name " << name << " is at floor: " << no_floor << " class: " << no_classroom;
};
Then main.cpp:
#include <iostream>
#include <cstring>
#include <study.h>
using namespace std;
int main(void)
{
//Student creation
int i,floor,classroom;
string stname;
Student* students[2];
for(i=0; i<2; i++)
{
cin >> stname;
cin >> floor;
cin >> classroom;
students[i] = new Student(stname, floor, classroom);
}
School sch;
for(i=0; i<2; i++)
{
sch.enter(students[i],i);
}
for(i=0; i<2; i++)
{
delete students[i];
}
}
Lastly the study.cpp function:
void School::enter(Student* student, int stc/*student counter*/)
{
pointer_array[stc] = student;
(pointer_array[stc])->print();
cout << " enters school!" << endl;
cout << "pointer array[" << stc << "]:" << pointer_array[stc] << endl;
}

Cout not printing out expected results

When I compile the below code, for some reason, the student/instructors name, age, and GPA/Rating, are not returned via their respective printPerson functions.
With the name variable, nothing is printed to the console.
With the age, GPA/Rating, console prints out a negative 8 digit number, and a negative float.
What am I not seeing?
Person.h
#pragma once
#ifndef PERSON_H
#define PERSON_H
#include <iostream>
#include <vector>
#include <string>
using std::string;
// Base class
class Person {
protected:
string name;
int age;
public:
void setName(string name);
void setAge(int age);
virtual void do_work(int number) {};
virtual void printPerson() {};
};
#endif;
Person.cpp
#include "Person.h"
#include <iostream>
#include <vector>
#include <string>
using std::cout;
using std::cin;
using std::endl;
void Person::setName(string name) {
name = name;
}
void Person::setAge(int age) {
age = age;
}
Student.h
#pragma once
#ifndef STUDENT_H
#define STUDENT_H
#include <iostream>
#include <vector>
#include <string>
#include "Person.h"
using std::string;
class Student : public Person {
private:
float gpa;
public:
void setGPA(float gpa);
float getGPA();
void do_work(int number);
void printPerson();
};
#endif;
Student.cpp
#include "Student.h"
#include <iostream>
#include <vector>
#include <string>
using std::string;
using std::cout;
using std::cin;
using std::endl;
void Student::setGPA(float gpa) {
gpa = gpa;
}
float Student::getGPA() {
return gpa;
}
void Student::do_work(int number) {
//cout << name << ".. " << number << "hours of homework.” << endl;
cout << name;
}
void Student::printPerson() {
cout << "Name : " << name << "Age :" << age << " GPA : " << getGPA() << endl;
}
Instructor.h
#pragma once
#ifndef INSTRUCTOR_H
#define INSTRUCTOR_H
#include <iostream>
#include <vector>
#include <string>
#include "Person.h"
class Instructor : public Person {
private:
float rating;
public:
void setRating(float rating);
float getRating();
void do_work(int number);
void printPerson();
};
#endif;
Instructor.cpp
#include "Instructor.h"
#include <iostream>
#include <vector>
#include <string>
using std::string;
using std::cout;
using std::cin;
using std::endl;
void Instructor::setRating(float rating) {
rating = rating;
}
float Instructor::getRating() {
return rating;
}
void Instructor::do_work(int number) {
cout << name << "graded papers for" << number << "hours." << endl;
}
void Instructor::printPerson() {
cout << " Name : " << name << " Age : " << age << " Rating : " << getRating() << endl;
}
University.h
#pragma once
#ifndef UNIVERSITY_H
#define UNIVERSITY_H
#include <iostream>
#include <vector>
#include <string>
#include "Person.h"
#include "Building.h"
#include "Student.h"
using std::cout;
using std::string;
using std::vector;
class University {
public:
string name;
vector<Person*> persons;
vector<Building> buildings;
public:
void printAllBuildings();
void printAllPersonsRecord();
};
#endif;
University.cpp
#include "University.h"
#include <iostream>
#include <vector>
#include <string>
using std::string;
using std::cout;
using std::cin;
using std::endl;
void University::printAllBuildings() {
cout << " Building Details : " << endl;
for (int j = 0; j < buildings.size(); j++) {
buildings[j].printBuilding();
}
}
void University::printAllPersonsRecord() {
cout << " Persons Details : " << endl;
for (int i = 0; i < persons.size(); i++) {
persons[i]->printPerson();
}
}
Building.h
#pragma once
#ifndef BUILDING_H
#define BUILDING_H
#include <iostream>
#include <vector>
#include <string>
#include "Person.h"
class Building {
public:
string name;
int size;
string address;
public:
void printBuilding();
};
#endif;
Building.cpp
#include "Building.h"
#include <iostream>
#include <vector>
#include <string>
using std::string;
using std::cout;
using std::cin;
using std::endl;
void Building::printBuilding() {
cout << " Name : " << name << " Address : " << address << endl;
}
main.cpp
#include "University.h"
#include "Person.h"
#include "Student.h"
#include "Instructor.h"
#include <iostream>
#include <vector>
#include <string>
using std::string;
using std::cout;
using std::cin;
using std::endl;
int main() {
Student student;
Instructor instructor;
student.setName("deepak");
student.setAge(12);
student.setGPA(12.0);
instructor.setName("rajdev");
instructor.setAge(23);
instructor.setRating(5.0);
Building building;
building.name = "block1";
building.size = 2000;
building.address = "noida sector-2";
Building building2;
building2.name = "block2";
building2.size = 4000;
building2.address = "noida sector-2";
University university;
university.name = "Oregon State University";
university.persons.emplace_back(&student);
university.persons.emplace_back(&instructor);
university.buildings.push_back(building);
university.buildings.push_back(building2);
university.printAllBuildings();
university.printAllPersonsRecord();
int choice;
bool isValidMainChoice = false;
while (!isValidMainChoice) {
cout << "Kindly choose one of the option from follwoing list of operations or Menu" << endl;
cout << "1 : Prints names of all the buildings" << endl;
cout << "2 : Prints names of everybody at the university" << endl;
cout << "3 : Choose a person to do work" << endl;
cout << "4 : Exit the program" << endl;
cin >> choice;
cout << "The value you entered is " << choice << endl;
if (choice == 1) {
university.printAllBuildings();
}
else if (choice == 2) {
university.printAllPersonsRecord();
}
else if (choice == 3) {
int personChoice;
bool isInputValid = false;
while (!isInputValid) {
cout << "Kindly choose the one of the following option to provide person's details." << endl;
cout << "5 : Student" << endl;
cout << "6 : Instructor" << endl;
cin >> personChoice;
if (personChoice == 5) {
isInputValid = true;
string studentName;
bool isValidName = false;
while (!isValidName) {
cout << " Kindly enter Name of the student :" << endl;
cin >> studentName;
if (studentName.length() == 0) {
cout << " Name must not be blank. Kindly re-enter the student's name." << endl;
}
else {
isValidName = true;
}
}
int age1 = 0;
bool isValidAge1 = false;
while (!isValidAge1) {
cout << " Kindly enter age of the student :" << endl;
cin >> age1;
if (age1 < 0 || age1 > 100) {
cout << " Age must be geter than 0 or lessa then 100. Kindly re-enter the student's age." << endl;
}
else {
isValidAge1 = true;
}
}
float gpa;
bool isValidGPA = false;
while (!isValidGPA) {
cout << " Kindly enter GPA of the student :" << endl;
cin >> gpa;
if (gpa < 0.0 || gpa > 4.0) {
cout << " GPA must be geter than 0.0 or less then 4.0. Kindly re-enter the Student GPA." << endl;
isValidGPA = false;
}
else {
isValidGPA = true;
}
}
Student student;
student.setName(studentName);
student.setAge(age1);
student.setGPA(gpa);
university.persons.emplace_back(&student);
university.printAllPersonsRecord();
}
else if (personChoice == 6) {
isInputValid = true;
string instructorName;
bool isValidName = false;
while (!isValidName) {
cout << " Kindly enter Name of the instructor :" << endl;
cin >> instructorName;
if (instructorName.length() == 0) {
cout << " Name must not be blank. Kindly re-enter the instructor's name." << endl;
}
else {
isValidName = true;
}
}
float rating;
bool isValidRating = false;
while (!isValidRating) {
cout << " Kindly enter rating of the instructor :" << endl;
cin >> rating;
if (rating < 0.0 || rating > 5.5) {
cout << " rating must be geter than 0.0 or less then 5.5. Kindly re-enter the instructor rating." << endl;
isValidRating = false;
}
else {
isValidRating = true;
}
}
int age2 = 0;
bool isValidAge2 = false;
while (!isValidAge2) {
cout << " Kindly enter age of the instructor :" << endl;
cin >> age2;
if (age2 < 0 || age2 > 100) {
cout << " Age must be geter than 0 or lessa then 100. Kindly re-enter the instructor's age." << endl;
}
else {
isValidAge2 = true;
}
}
Instructor instructor;
instructor.setName(instructorName);
instructor.setAge(age2);
instructor.setRating(rating);
university.persons.emplace_back(&instructor);
}
else {
cout << "The value you entered is incorrct.Please r-enter the values." << endl;
}
}
}
else if (choice == 4) {
isValidMainChoice = true;
cout << " You are exits from system. Thanks You !!" << endl;
}
}
return 0;
};
Please modify all your code for setter
void Person::setName(string name) {
//before-edit: name = name;
this->name = name; //OR Person::name = name;
}
As the local string name parameter and your class variable are the same, you expect the parameter are passed correctly, but it doesn't.

C++ Using array and for loop to output from multiple classes

I am asked to do this code and i need to use array or something similar to print out different classes. The only way i know is individually doing every single class is there a faster way of doing this. Following is the way i am using at the moment.
Ground_Transport Gobj;
Air_Transport Aobj;
Sea_Transport Sobj;
Car Cobj;
Train Tobj;
Bus Bobj;
Gobj.estimate_time();
Gobj.estimate_cost();
cout << Gobj.getName() << endl;
Bobj.estimate_time();
Bobj.estimate_cost();
cout << Bobj.getName() << endl;
Sobj.estimate_time();
Sobj.estimate_cost();
cout<<Sobj.getName()<<endl;
Aobj.estimate_time();
Aobj.estimate_cost();
cout << Aobj.getName() << endl;
Cobj.estimate_time();
Cobj.estimate_cost();
cout << Cobj.getName() << endl;
Tobj.estimate_time();
Tobj.estimate_cost();
cout << Tobj.getName() << endl;
Transport_KL_Penang Kobj;
cout << Kobj.getName() << endl;
This is the header file Transport_KL_Penang
#include <iostream>
#include <string>
using namespace std;
class Transport_KL_Penang
{
public:
Transport_KL_Penang() {}
virtual string getName() {
return Name;
}
int Time_in_hours1 ;
int Time_in_hours2 ;
int Cost_in_RM1 ;
int Cost_in_RM2 ;
void estimate_time() ;
void estimate_cost() ;
private:
static string Name;
};
void Transport_KL_Penang::estimate_time()
{
cout << "It takes " << Time_in_hours1 << "-" << Time_in_hours2 <<
" hours if you use " << Name << endl;
}
void Transport_KL_Penang::estimate_cost()
{
cout << "It will cost around " << Cost_in_RM1 << "-" << Cost_in_RM2 <<
"RM if you use " << Name << endl;
}
If you don't need a specific object name, you can write something as a code below, creating a multiples generics objects:
#include <iostream>
#include <cstdlib>
#include <time.h>
class Myclass {
private:
int randTime;
float cost;
public:
void estimate_time(){
randTime = rand()%100;
}
void estimate_cost(){
cost = randTime * 0.2;
}
float getEstimateCost(){
return cost;
}
};
int main(){
srand(time(NULL));
int numberOfObjects = 7;
Myclass obj[numberOfObjects];
//input
for(int i = 0; i < numberOfObjects; i++){
obj[i].estimate_time();
obj[i].estimate_cost();
}
// printing
for(int i = 0; i < numberOfObjects; i++){
std::cout << obj[i].getEstimateCost() << std::endl;
}
return 0;
}

Class Header , string does not name a type

Hi I'm trying to finish my homework. I have a compilation error when I try to separate a class, then call it later. But the whole test function works properly. It has the class within the whole text. Basically when i try to separate the class from the text, I have an error message.
#include <iostream>
#include<string>
using namespace std;
class Person
{
private:
string alpha;
int beta;
public:
Person(string Name, int Age)
{
alpha = Name;
beta = Age;
}
string getName()
{
return alpha;
}
int getAge()
{
if (beta < 0)
{ beta = 0;
cout << "Error. A negative age cannot be entered. " << endl;
}
if (beta > 120)
{
cout << "Damn you're old. How many heart transplants have you had? You Vampire " << endl;
}
return beta;
}
void setName(string alpha)
{
}
void setAge(int beta);
void display();
};
int main()
{
Person Lu("Jess ", 22);
Person Rose("Gary ", 49);
cout << Lu.getAge() << " " << Lu.getName() <<endl;
cout << Rose.getAge() << " " << Rose.getName() << endl;
return 0;
}`
But when i separate the class,:
#include <iostream>
#include <string>
class Person
{
private:
string alpha;
int beta;
public:
Person(string Name, int Age)
{
alpha = Name;
beta = Age;
}
string getName()
{
return alpha;
}
int getAge()
{
if (beta < 0)
{ beta = 0;
cout << "Error. A negative age cannot be entered. " << endl;
}
if (beta > 120)
{
cout << "Damn you're old. How many heart transplants have you had? You Vampire " << endl;
}
return beta;
}
void setName(string alpha)
{
}
void setAge(int beta);
void display();
};
Main file
#include <iostream>
#include "Person.h"
#include <string>
using namespace std;
int main()
{
Person Lu("Jess ", 22);
cout << Lu.getAge() << " " << Lu.getName() <<endl;
return 0;
}`
But when I separate the class i get an error in codeblocks. Please help.
You forgot to put using namespace std; in Person.h.
Also, you don't have any header guards on Person.h, which won't cause a problem in such a simple program, but will as soon as multiple files include Person.h.