I am trying to write a class with 3 attribute and some constructors and following methods: set (h, m, s), Double getHousrs () operator +
correctTime(). To change e.g 1:76:84 to 2:13:13
Current code
#include <iostream>
using namespace std;
class duration {
public:
duration(int h, int m, int s)
:hour (h), minutes (m), seconds (s);
{}
void printDate()
{
cout << hour<< ":" << minutes << ":" << seconds << endl;
}
double getHours() {
return hours;
}
double getSeconds() {
return seconds;
}
private:
int hour;
int minutes;
int seconds;
duration operator+(duration &obj)
{ }
};
int main()
{
duration obj;
return 0;
}
The solution to your problem would be to add the values together which can be most efficiently done like this I also fixed all the other errors you had in your class:
#include <iostream>
using namespace std;
class duration {
public:
duration(int h, int m, int s)
:hour (h), minute (m), second (s)
{}
void printDate()
{
cout << hour<< ":" << minute << ":" << second << endl;
}
double getHours() {
return hour;
}
double getSeconds() {
return second;
}
duration operator + (const duration& other)
{
duration temp(0, 0, 0);
temp.second = (other.second+second)%60;
temp.minute = ((other.second + second)/60 + other.minute + minute)%60;
temp.hour = ((other.minute+minute)/60 + other.hour + hour)%60;
return temp;
}
private:
int hour;
int minute;
int second;
};
int main()
{
duration obj(3, 5, 10);
duration obj2(4, 55, 40);
duration temp = obj + obj2;
temp.printDate();
return 0;
}
Related
As I understand it(Jtime time1 = Jtime(1,2,4);), shouldn't the left and right sides of this statement call the constructor once
class Jtime
{
public:
Jtime(){ std::cout << "No argument constructor"; }
Jtime(double h, double M, double S)
{
std::cout << "There is a parameter constructor H M S";
Hours_ = h; Minte_ = M; Sencon_ = S;
}
~Jtime() = default;
private:
double Hours_;
double Minte_;
double Sencon_;
};
int main()
{
Jtime time1 = Jtime(1,2,4);
}
I got some problem when run my coding. I got 2 separate file to create RetailItem class and create main. I create both in project.
Below are main.cpp
//main
#include "retailitem.h"
#include <iostream>
#include <iomanip>
using namespace std;
using std::cout;
void displayItem(RetailItem *, const int);
int main()
{
const int Item = 3;
RetailItem ritem[Item] ={ { "Jacket", 12, 59.95 },
{ "Designer Jeans", 40, 34.95 },
{ "Shirt", 20, 24.95 } };
//cout << fixed << setprecision(2);
void displayItem(RetailItem *ritem, const int Item){
cout <<" DESCRIPTION UNITS ON HAND PRICE";
cout<<"=================================================================\n";
for (int i = 0; i < Item; i++)
{
cout << setw(12) << ritem[i].getDesc();
cout << setw(12) << ritem[i].getUnits();
cout << setw(8) << ritem[i].getPrice();
}
cout << "===================================================================";
}
return 0;
}
and there one more file retailitem.h
//RetailItem class
#include <string>
using namespace std;
class RetailItem
{
private:
string description;
int unitsOnHand;
double price;
public:
RetailItem(string,int,double);
void setDesc(string d);
void setUnits(int u);
void setPrice(double p);
string getDesc();
int getUnits();
double getPrice();
};
RetailItem::RetailItem(string desc, int units, double cost)
{
description = desc;
unitsOnHand = units;
price = cost;
}
void RetailItem::setDesc(string d)
{
description = d;
}
void RetailItem::setUnits(int u)
{
unitsOnHand = u;
}
void RetailItem::setPrice(double p)
{
price = p;
}
string RetailItem::getDesc()
{
return description;
}
int RetailItem::getUnits()
{
return unitsOnHand;
}
double RetailItem::getPrice()
{
return price;
}
when compile and run main,
[Error] a function-definition is not allowed here before '{' token
[Error] expected '}' at end of input
I don't know what to fix, how can I solve it?
The error message undoubtedly contained a line number that told you where the problem was. That's an important part of describing the problem. But here it happens to be obvious: void displayItem(RetailItem *ritem, const int Item){ is the start of a function definition. You can't define a function inside another function. Move this outside of main.
Hi I'm quite new to c++ and I have a project but to do but a question in the project requires me to add a function, getAverageCostPerDay(), which takes a vector of Reservations object and returns the average cost of a car reservation. How do I got about doing this? Thanks
Reservation.h
#pragma once
#include <string>
class Reservation
{
private:
int id;
std::string name;
int stDate;
int stMonth;
int stYear;
int duration;
float cost;
std::string licensePlate;
static int reservationCount;
public:
//Constructor
Reservation();
Reservation(int id, std::string name, int stDate, int stMonth, int
stYear, int duration, float cost, std::string licensePlate);
//Destructor
~Reservation();
//Getters
int getId();
std::string getName();
int getStDate();
int getStMonth();
int getStYear();
int getDuration();
float getCost();
std::string getLicensePlate();
//Setters
void setId(int id);
void setName(std::string name);
void setStDate(int stDate);
void setStMonth(int stMonth);
void setStYear(int stYear);
void setDuration(int duration);
void setCost(float cost);
void setLicensePlate(std::string licensePlate);
static int getReservationCount()
{
return reservationCount;
}
};
Reservation.cpp
#include "pch.h"
#include "Reservation.h"
int Reservation::reservationCount = 0;
//Constructor
Reservation::Reservation()
{
this->id = 0;
this->name = "";
this->stDate = 0;
this->stMonth = 0;
this->stYear = 0;
this->duration = 0;
this->cost = 0;
this->licensePlate = "";
reservationCount++;
}
Reservation::Reservation(int id, std::string name, int stDate, int stMonth,
int stYear, int duration, float cost, std::string licensePlate)
{
this->id = id;
this->name = name;
this->stDate = stDate;
this->stMonth = stMonth;
this->stYear = stYear;
this->duration = duration;
this->cost = cost;
this->licensePlate = licensePlate;
reservationCount++;
}
//Destructor
Reservation::~Reservation()
{
reservationCount--;
std::cout << "Destroying (" << this->name << ")" << std::endl;
}
//Getters
int Reservation::getId()
{
return this->id;
}
std::string Reservation::getName()
{
return this->name;
}
int Reservation::getStDate()
{
return this->stDate;
}
int Reservation::getStMonth()
{
return this->stMonth;
}
int Reservation::getStYear()
{
return this->stYear;
}
int Reservation::getDuration()
{
return this->duration;
}
float Reservation::getCost()
{
return this->cost;
}
std::string Reservation::getLicensePlate()
{
return this->licensePlate;
}
//Setters
void Reservation::setId(int id)
{
this->id = id;
}
void Reservation::setName(std::string name)
{
this->name = name;
}
void Reservation::setStDate(int stDate)
{
this->stDate = stDate;
}
void Reservation::setStMonth(int stMonth)
{
this->stMonth = stMonth;
}
void Reservation::setStYear(int stYear)
{
this->stYear = stYear;
}
void Reservation::setDuration(int duration)
{
this->duration = duration;
}
void Reservation::setCost(float cost)
{
this->cost = cost;
}
void Reservation::setLicensePlate(std::string licensePlate)
{
this->licensePlate = licensePlate;
}
Main.cpp
#include "pch.h"
#include "Reservation.h"
//Regular Expressions
std::string idRegexStr = "[0-9]{3,4}";
std::string nameRegexStr = "[A-Za-z]{1}[a-z]{1,30} [A-Za-z]{1}[a-z]{1,30}";
std::string stDateRegexStr = "[0-3]{1}[0-9]{1}";
std::string stMonthRegexStr = "[0-1]{1}[0-9]{1}";
std::string stYearRegexStr = "[1-2]{1}[0-9]{1}[0-9]{1}[0-9]{1}";
std::string durationRegexStr = "[1-9]{1}[0-9]{1}";
std::string costRegexStr = "[0-9]{2}.[0-9]{2}";
std::string licencePlateRegexStr = "[0-9]{2,3}\\s*[A-Z]{2,3}\\s*[0-9]+";
//Validates data against a user-defined string
bool validate(std::string regexStr, std::string data)
{
return std::regex_match(data, std::regex(regexStr));
}
std::vector<Reservation>populateVector(Reservation defaultVector, int size)
{
std::vector<Reservation> outVector;
for (int i = 0; i < size; i++)
{
outVector.push_back(defaultVector);
}
return outVector;
}
double getAverageCostPerDay(const std::vector<Reservation> outVector)
{
double average = 0;
for (std::size_t i = 0; i < outVector.size(); i++)
{
average = std::vector<Reservation>outVector.at(float cost);
}
return true;
}
int main()
{
/*
//these were example values to see if regex works
bool idIsValid = validate(idRegexStr, "101");
bool nameIsValid = validate(nameRegexStr, "John Smith");
bool stDateIsValid = validate(stDateRegexStr, "24");
bool stMonthIsValid = validate(stMonthRegexStr, "10");
bool stYearIsValid = validate(stYearRegexStr, "2018");
bool durationIsValid = validate(durationRegexStr, "10");
bool costIsValid = validate(costRegexStr, "22.50");
bool licenseIsValid = validate(licencePlateRegexStr, "181 LH 555");
std::cout << "Invalid = 0 / Valid = 1\n";
std::cout << "\n";
std::cout << "Valid ID: " << idIsValid << std::endl;
std::cout << "Valid Name: " << nameIsValid << std::endl;
std::cout << "Valid Start Date: " << stDateIsValid << std::endl;
std::cout << "Valid Start Month: " << stMonthIsValid << std::endl;
std::cout << "Valid Start Year: " << stYearIsValid << std::endl;
std::cout << "Valid Duration: " << durationIsValid << std::endl;
std::cout << "Valid Cost: " << costIsValid << std::endl;
std::cout << "Valid License: " << licenseIsValid << std::endl;
*/
Reservation r1(101, "John Smith", 24, 10, 2018, 4, 22.50, "181 LH
5555");
Reservation r2(102, "Jane Caroll", 31, 01, 2017, 6, 34.25, "161 DUB
55454");
Reservation r3(103, "Sean Morrissey", 16, 06, 2014, 2, 67.50, "162 WEX
83675");
Reservation r4(104, "Billy Joe", 04, 03, 2016, 8, 51.20, "152 DUB
10347");
std::cout << "Reservation Count: " << Reservation::getReservationCount()
<<
std::endl;
}
There are a couple of ways to do this.
You could wrap your vector of reservations inside of a class and keep track of how many there are, what the total cost is, and calculate the average.
However, if you have to return this information through the Reservation class, then you'll have to use a static variable for sum of costs and number of reservation objects. Static attributes are available in all objects of that class and will have the same value between all objects. So, every time you create a Reservation object, increment the count and sum of costs. Then when you need the average, you can calculate it from any of the objects or through the class (if you make a static function to do this).
In this code I have an object that contains two variables hours and minutes. Im trying to consecutively add a value of 15 minutes and a value of 20 minutes to an object called t1. But I get the error : left of '.plus' must have class/struct/union.
Thanks in advance.
#include <iostream>
#include <iomanip>
using namespace std;
class Time {
public:
Time(int u, int m);
Time(int g);
void plus(Time t);
void plus(int x);
void print();
private:
int min;
int hour;
};
void Time::plus(Time t) {
min += t.min;
if (min > 59) {
hour++;
min = min - 60;
}
}
void Time::plus(int x) {
min += x;
if (min > 59) {
hour++;
min = min - 60;
}
}
void Time::print() {
cout << setw(2) << hour << " hour and " << min << " minutes";
}
Time::Time(int u, int m) : hour(u), min(m) {
}
Time::Time(int m) : hour(0), min(m) {
}
int main() {
Time t1(1, 10);
const Time kw(15);
t1.plus(kw).plus(20);
cout << "t1 = "; t1.print(); cout << endl;
cin.get();
return 0;
}
Right now, your plus returns void, or nothing! So you can't do t1.plus(kw).plus(20);. If you want to, you need to have your .plus() return a Time:
class Time {
public:
Time &plus(Time t);
Time &plus(int x);
...
};
I've gone ahead and made it return a Time by reference so that when you chain the function like you are, the next plus will still modify the original object the first plus was called on! We can do this if you implement the plus functions like:
Time &Time::plus(Time t) {
min += t.min;
if (min > 59) {
hour++;
min = min - 60;
}
return *this; //return ourselves so that the next func will be called on us too!
}
Time &Time::plus(int x) {
min += x;
if (min > 59) {
hour++;
min = min - 60;
}
return *this; //return ourselves so that the next func will be called on us too!
}
I need to write the name, act# balance and address of the object that is stored in the vector, to a file.
I believe I have the program to push the objects into the vectors, but since they are vectors of object pointers I am having problems figure out how to call the object and print all 3 objects out.
Main.cpp
vector<Account*> accounts;
accounts.push_back(new Savings(new Person("Bilbo Baggins", "43 Bag End"), 1, 500, 0.075));
accounts.push_back(new Checking(new Person("Wizard Gandalf", "Crystal Palace"), 2, 1000.00, 2.00));
accounts.push_back(new Savings(new Person("Elf Elrond", "Rivendell"), 3, 1200, 0.050));
ofstream outFile;
outFile.open("accounts.txt");
if (outFile.fail())
{
cout << "\nYour file did not open, the program will now close!\n";
system("PAUSE");
return 0;
}
else
{
cout << "\nBINGO!!! It worked.\n\n";
system("PAUSE");
cout << "\n";
}
// New : Using a loop, send messages to each of the three Account objects to write themselves out to the file.
cout << "\nNow we are going to write the information to \"Accounts.txt\" \n\n";
system("PAUSE");
for (int i = 0; i < accounts.size(); i++) {
accounts[i]->writeAccount(outFile);
}
Account.h
#pragma once
#include <string>
#include <iostream>
#include "Person.h"
using namespace std;
// Account class - abstract/parent class
class Account
{
private:
int actNumber;
double actBallance;
Person PersonName;
public:
Account();
Account(int, double, Person*);
int getActNumber();
virtual double getActBallance();
string getName();
string getAdd();
void deposit(double);
void withdrawl(double);
virtual void writeAccount(ofstream&);
virtual void readAccount(ifstream&);
void testAccount(int i);
};
// Checking class: inherits from the Account class
class Checking : public Account
{
private:
double monthlyFee;
public:
Checking();
Checking(Person*, int, double, double);
void setMonthlyFee(double);
double getActBallance();
void writeAccount(ofstream&);
void readAccount(ifstream&);
};
// Savings class: inherits from the Account class
class Savings : public Account
{
private:
int interestRate;
public:
Savings();
Savings(Person*, int, double, double); // person, act#, Ballance, Interest Rate
void setInterestRate(double);
double getActBallance();
void writeAccount(ofstream&);
void readAccount(ifstream&);
};
Account.cpp
#include "Account.h"
#include <string>
using namespace std;
Account::Account()
{
actNumber = 0;
actBallance = 0.0;
}
Account::Account(int act, double bal, Person* name)
{
actNumber = act;
actBallance = bal;
}
int Account::getActNumber()
{
return actNumber;
}
double Account::getActBallance()
{
return actBallance;
}
string Account::getName()
{
return PersonName.getName();
}
string Account::getAdd()
{
return PersonName.getAddress();
}
void Account::deposit(double money)
{
actBallance += money;
}
void Account::withdrawl(double money)
{
actBallance -= money;
}
void Account::writeAccount(ofstream& output)
{
output << actNumber << "\n" << actBallance << "\n" << PersonName.getName() << "\n" << PersonName.getAddress() << endl;
}
void Account::readAccount(ifstream& output)
{
output >> actNumber;
output >> actBallance;
}
// Checking Account
Checking::Checking() {
monthlyFee = 0;
}
Checking::Checking(Person* per, int actNum, double bal, double interest) {
bal -= monthlyFee;
Account:Account(actNum, bal, per);
}
void Checking::setMonthlyFee(double fee) {
monthlyFee = fee;
}
double Checking::getActBallance() {
double ballance = Account::getActBallance();
return ballance = monthlyFee;
}
void Checking::readAccount(ifstream& output) {
int actNumber = Account::getActNumber();
int actBallance = Account::getActBallance() - monthlyFee;
output >> actNumber;
output >> actBallance;
}
void Checking::writeAccount(ofstream& output) {
int actNumber = Account::getActNumber();
int actBallance = Account::getActBallance();
output << actNumber << "\n" << actBallance << endl;
}
// Savings Account
Savings::Savings() {
interestRate = 0;
}
// Savings(Person, int, double, double) // person, act#, Ballance, Interest Rate
Savings::Savings(Person* per, int actNum, double bal, double interest) {
bal += (bal * interest);
Account:Account(actNum, bal, per);
}
void Savings::setInterestRate(double rate) {
interestRate = rate;
}
double Savings::getActBallance() {
double ballance = Account::getActBallance();
return ballance + (ballance * interestRate);
}
void Savings::readAccount(ifstream& output) {
double actBallance = Account::getActBallance();
int actNumber = Account::getActNumber();
actBallance += (actBallance * interestRate);
output >> actNumber;
output >> actBallance;
}
void Savings::writeAccount(ofstream& output) {
int actNumber = Account::getActNumber();
int actBallance = Account::getActBallance();
output << actNumber << "\n" << actBallance << endl;
}
I realize I am so far off... but I have been at this for HOURS and I can not figure out for the life of me, but to take the vector of object pointers and output the objects values.
Person.h
#pragma once
#include <string>
#include <fstream>
using namespace std;
class Person
{
private:
string name;
string address;
public:
Person();
Person(string a, string b);
string getName();
string getAddress();
void writePerson(ofstream&);
void readPerson(ifstream&);
};
Person.cpp
#include "Person.h"
#include <string>
using namespace std;
Person::Person()
{
name = "NAME";
address = "123 STREET";
}
Person::Person(string a, string b)
{
name = a;
address = b;
}
string Person::getName()
{
return name;
}
string Person::getAddress()
{
return address;
}
void Person::writePerson(ofstream& output)
{
output << name << " " << address << endl;
}
void Person::readPerson(ifstream& output)
{
output >> name;
output >> address;
Person(name, address);
}
Read again your course books on constructors: there are severe issues in all of your constructors. As a result, you don't initialize the object member variables, and you effectively end up printing lots of zeros and empty strings...
Firstly, for your base-class, you must initialize the person name. You should have written:
Account::Account(int act, double bal, Person* name)
: actNumber(act)
, actBallance(bal)
, PersonName(name)
{}
Secondly, for your derived classes, the initialisation of the base-class must be done in the initializer-list, not in the body of the ctor. Here is for exemple the correct definition for the Checking's ctor:
Checking::Checking(Person* per, int actNum, double bal, double interest)
: Account(actNum, bal, per)
, monthlyFee(-bal)
{}
Thirdly, be careful to initialize the member variables with the arguments of the ctor. You sometimes do the opposite and assign the ctor arguments with the (uninitialized) member variables.
BTW, Account is a base-class for a polymorphic hierarchy: thus, the Account destructor must be declared virtual.