I have to make a program to display the weather in Sheffield since 1930.
I have to use sheffield.data for the record.
I have 3 files. Data.cpp, Data.hpp and analyze.cpp
analyze.cpp:
#include <istream>
#include <fstream>
#include <vector>
#include "data.hpp"
using namespace std;
int main()
{
MonthData data();
vector<MonthData> vectorData;
ifstream file ("sheffield.data");
string line;
int l_num = 0;
if (file.is_open()) {
while (getline(file, line))
if (l_num < 4) {
l_num += 1;
}
else {
file >> data;
vectorData.push_back(data);
}
float MinimumDeg = vectorData[0].getMinimum();
int year = vectorData[0].getYear();
for ( size_t a = 0; a < vectorData.size(); a++)
{
MinimumDeg = vectorData[a].getMinimum();
year = vectorData[a].getYear();
}
cout << "Lowest year and month lowest rainfall: '\n'" << "Min Temp;" << MinimumDeg << "C '\n'" << "Year" << year << endl;
return 0;
}
}
:
data.cpp
#include "data.hpp"
#include <iostream>
using namespace std;
istream& operator >> (istream& in, MonthData& data)
{
in >> data.year >> data.year >> data.temp_maximum >> data.temp_minimum >> data.air_frost >> data.rain >> data.sun;
return in;
}
data.hpp:
#ifndef DATA_HPP
#define DATA_HPP
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
class MonthData
{
friend istream& operator >> (istream&, MonthData&);
public:
//overload constructor
MonthData(double, int, double, double, int, double, double);
//Accessor functions
double getYear() const { return year; } //returns the year
int getMonth() const { return month; } //returns the month
double getMaximum() const { return temp_maximum; } //returns maximum temperature
double getMinimum() const { return temp_minimum; } //returns minimum temperature
int getFrost() const { return air_frost; } //returns air frost
double getRain() const { return rain; } //returns rainfall
double getSun() const { return sun; } //returns no of hours of sunshine
private:
double year;
double month;
double temp_maximum;
double temp_minimum;
int air_frost;
double rain;
double sun;
};
#endif
Why am I getting this error?
[sc14da#cslin035 cw]$ g++ data.cpp data.hpp analyze.cpp -o analyze
analyze.cpp: In function ‘int main()’:
analyze.cpp:11: error: no matching function for call to ‘MonthData::MonthData()’
data.hpp:17: note: candidates are: MonthData::MonthData(double, int, double, double, int, double, double)
data.hpp:12: note: MonthData::MonthData(const MonthData&)
If you do not provide any constructor in your class, the compiler will automatically create one for you.
In your class, you have specified a particular constructor:
MonthData(double, int, double, double, int, double, double);
As soon as you provide any constructor, the compiler will not create a default constructor (i.e. one that takes no parameters).
You are calling
MonthData data();
You are passing no parameters here but you have no constructor that takes no parameters.
You probably meant to call
MonthData data(with 7 parameters);
Alternatively, add the following to your MonthData class body:
MonthData();
Then in your data.cpp, need to provide the code for what this constructor should do, i.e.
MonthData::MonthData()
{
//Initialise as required - but better to use a member initialization list
}
It would be better to use a member initialization list for your 7 member variables.
For example:
MonthData::MonthData()
: year(2014), month(2), temp_maximum(15.4), temp_minimum(2.1), air_frost(5), rain(5.6), sun(7.6) //Use desired default values
{}
This simple constructor code could instead be put directly in the class body in the header file:
class MonthData
{
public:
//overload constructor
MonthData(double y, int m, double max, double min, int fr, double r, double s)
: year(y), month(m), temp_maximum(max), temp_minimum(min), air_frost(fr), rain(r), sun(s) {};
//default constructor
MonthData()
: year(2014), month(2), temp_maximum(15.4), temp_minimum(2.1), air_frost(5), rain(5.6), sun(7.6) {};
etc
};
In addition - review your variable types. Should year really be a double? Also you have month declared as a double but your accessor returns an int.
That's not surprising as you haven't included a default constructor. Or, more specifically, a constructor that matches this line:
MonthData data();
Solution: add a default constructor in your base MonthData class (data.hpp).
Related
I am trying to create a class object s2 with some customized attributes and some attributes from default constructor however my output is the wrong output for the get_year function. It should be outputing 0 which is the key for FRESHMAN but it is out putting 2 instead. The rest of the code is outputting as expected:
#include <stdio.h>
#include <iostream>
#include <algorithm> // for std::find
#include <iterator> // for std::begin, std::end
#include <ctime>
#include <vector>
#include <cctype>
using namespace std;
enum year {FRESHMAN, SOPHOMORE, JUNIOR, SENIOR};
struct name
{
string firstName;
string lastName;
friend std::ostream& operator <<(ostream& os, const name& input)
{
os << input.firstName << ' ' << input.lastName << '\n';
return os;
}
};
class Student: name{
private:
name Name;
year Year;
int idNumber;
string Department;
public:
void setname(string fn="", string ln="")
{
Name.firstName =fn;
Name.lastName =ln;
}
name get_name()
{
return Name;
}
void set_year(year yr=FRESHMAN)
{
Year=yr;
}
year get_year()
{
return Year;
}
void set_ID(int ID=0)
{
idNumber=ID;
}
int get_ID()
{
return idNumber;
}
void set_Department(string Dept="")
{
Department=Dept;
}
string get_Department()
{
return Department;
}
};
int main()
{
Student s2;
s2.setname("Nikolai", "Khabeboolin");
s2.set_ID(12436193);
cout<<"ID is: "<< s2.get_ID()<<", name is "<< s2.get_name()<<", year in school is: "<<s2.get_year()<<", Department is "<<s2.get_Department()<<endl;
return 0;
}
Student lacks a constructor, so all its members are default initialized, and the default initialization of year Year and int idNumber is "no initialization", so reading from them is undefined behavior. Reading them might find 0, 2, a random value each time, or crash.
I see that your class contains a void set_year(year yr=FRESHMAN) member, but your code never called set_year, so no part of this executed.
You should make a default constructor for Student, or as Goswin von Brederlow stated, use year Year{FRESHMAN}; and int idNumber{-1}; when declaring the members, to give them default initializations.
By not explicitly declaring and defining a constructor, in this case Student(), you open yourself up to undefined behavior. Your constructor should call set_year(year yr=FRESHMAN) OR even better, just set the year itself.
I need to create an ADT for an assignment. I have my class definition in a header file as follows:
#ifndef PHONECALL_H
#define PHONECALL_H
#include <iostream>
using namespace std;
class PhoneCall
{
public:
PhoneCall();
PhoneCall(string newNumber);
~PhoneCall();
string getNumber()const;
int getLength()const;
float getRate()const;
float calcCharge(); //calcuates total cost of call
friend bool operator==(const PhoneCall & call1, const PhoneCall & call2);
friend istream& operator >>(istream& in, PhoneCall& call);
friend ostream& operator <<(ostream& out, const PhoneCall& call);
private:
string number;
int length;
float rate;
};
All the bodies of the functions are in the implementation file (no errors there)
Then in the main application file, when I call the calcCharge() function, I get:
error: 'calcCharge()' was not declared in this scope
This is the only error I get. Here is the application file code:
#include <iostream>
#include <fstream>
#include "PhoneCall.h"
using namespace std;
int main()
{
string num, cellNum;
int length;
float rate, total;
cout << "Enter a phone number: " << endl;
cin>> num;
PhoneCall theCall(num);
ifstream read;
while (read >> cellNum >> length >> rate)
{
if (cellNum == num)
{
total += calcCharge();
}
}
return 0;
}
I know the code for the main application is incomplete, but due to this error I am not able to test whether the program is doing what I need it to do.
It's a member of the class.
total += theCall.calcCharge();
So I am trying to read in a file using private class variables. I am unsure how to display the file. There might be another way to do this, but this is what I could think of. Note, its my first project using classes and private and public/private members. Was I on the right path atleast? I keep getting an error for the int main function. How can I fix it?
This is my main:
#include "Record.h"
#include <sstream>
int main ()
{
Record employee;
ifstream myFile;
myFile.open("Project 3.dat");
string str;
int i=0;
if (myFile.is_open())
{
while (getline(myFile, str))
{
istringstream ss(str);
ss >> employee.get_name(str) >> employee.get_id(stoi(str)) >>
employee.get_rate(stoi(str)) >> employee.get_hoursWorked(stoi(str));
}
}
return 0;
}
This is my header:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class Record
{
private:
string name;
int id;
double rate;
double hours;
public:
Record();
Record (string n, int empid, double hourlyRate, double hoursWorked);
// constructor
void read_data_from_file();
double calculate_wage();
void print_data();
/* ASETTERS AND GETTERS */
void set_name (string n);
string get_name();
void set_id (int empid);
int get_id();
void set_rate (double hourlyRate);
double get_rate();
void set_hoursWorked(double hoursWorked);
double get_hoursWorked();
/* END OF SETTERS AND GETTERS */
};
This is my cpp
#include "Record.h"
Record::Record():name(), id(0), rate(0), hours(0) {} //default constructor
must be implemented first
Record::Record(string n, int empid, double hourlyRate, double hoursWorked)
{
name = n;
empid = id;
hourlyRate = rate;
hoursWorked = hours;
}
//
void Record::set_name(string n)
{
name = n;
}
string Record::get_name()
{
return name;
}
//
void Record::set_id(int empid)
{
id = empid;
}
int Record::get_id()
{
return id;
}
//
void Record::set_rate(double hourlyRate)
{
rate = hourlyRate;
}
double Record::get_rate()
{
return rate;
}
//
void Record::set_hoursWorked(double hoursWorked)
{
hours = hoursWorked;
}
double Record::get_hoursWorked()
{
return hours;
}
//
double Record::calculate_wage()
{
return (rate * hours);
}
There are some issues with your code that I can see. most of your problems aren't related to your question (I mean using a class or private/public members). you have more basic misunderstandings. So here's some explanation that might help you:
1- Using functions : You have some troubles using your defined functions, A function can have multiple input parameters and one return value. basically it's like this return_type function_name(parameter_type param1, ...). it means that if you call this function you need to pass param1,... and expect your function operation and then have a return value of return_type. You defined some set and get functions. if you want to set something you should call set function and pass your desired value to it and it will copy your value to your defined member data, after that you can call get function to retrieve that value. So when you call get function with parameter it will raise error. Here you want to call set function.
2- Using stoi : As you can see you are getting error on using stoi function too, this is a function for converting string to integer, The thing that you missed here is that this function declared in std namespace. If you want to use it you need to use it like this std::stoi(str). one other thing, using namespace std is a bad practice.
3- Design matters : In OOP design, a class must have a purpose and an actual job to do. It might be an interface to abstract class but a bunch of set and get functions will not fulfill the need to create a class. Here if your class is going to do file operations, it's OK, but as far as you shared your code it's just some set and get functions.
Based on my Snack.cpp, Snack header file, MiniVend header file & miniVend.cpp file, I am trying to move my Snack private member - price into my MiniVend.cpp file to generate the amount * price to return a total value of items in my machine. How do I access the price from another class?
Portion of my miniVend.cpp file
double miniVend::valueOfSnacks()
{
return //// I don't know how to get snacks price in here? I need to access snacks & getSnackPrice.
}
miniVend header
#ifndef MINIVEND
#define MINIVEND
#include <string>
#include "VendSlot.h"
#include "Snack.h"
using std::string;
class miniVend
{
public:
miniVend(VendSlot, VendSlot, VendSlot, VendSlot, double); //constructor
int numEmptySlots();
double valueOfSnacks();
//void buySnack(int);
double getMoney();
~miniVend(); //desructor
private:
VendSlot vendslot1; //declare all the vending slots.
VendSlot vendslot2; //declare all the vending slots.
VendSlot vendslot3; //declare all the vending slots.
VendSlot vendslot4; //declare all the vending slots.
double moneyInMachine; //money in the machine
};
#endif // !MINIVEND
Snack.cpp
#include "Snack.h"
#include <iostream>
#include <string>
using std::endl;
using std::string;
using std::cout;
using std::cin;
Snack::Snack() //default constructor
{
nameOfSnack = "bottled water";
snackPrice = 1.75;
numOfCalories = 0;
}
Snack::Snack(string name, double price, int cals)
{
nameOfSnack = name;
snackPrice = price;
numOfCalories = cals;
}
Snack::~Snack()
{
}
string Snack::getNameOfSnack()
{
return nameOfSnack;
}
double Snack::getSnackPrice()
{
return snackPrice;
}
int Snack::getNumOfCalories()
{
return numOfCalories;
}
Snack.h file
#ifndef SNACK_CPP
#define SNACK_CPP
#include <string>
using std::string;
class Snack
{
private:
string nameOfSnack;
double snackPrice;
int numOfCalories;
public:
Snack(); //default constructor
Snack(string name, double price, int cals); //overload constructor
~Snack(); //destructor
//Accessor functions
string getNameOfSnack(); //returns name of snack
double getSnackPrice(); //returns the price of the snack
int getNumOfCalories(); //returns number of calories of snack
};
#endif // !SNACK_CPP
Assuming getSnackPrice() is public, and Snack.h does exist, you should just be able to call
snackObject.getSnackPrice() * ammount
what you need is friend keyword. Define the
friend class className;
I don't really understand why you don't just implement get()? Accessing private data is really bad. You are breaking the encapsulation. But if you really want to know (i.e. you should NOT do it, it is really BAD), then you just return a reference to a private data as shown below
#include <iostream>
class A
{
public:
A(int a) : x(a) {}
int &getPrivateDataBAD() { return x; }
void print() { std::cout << x << std::endl; }
private:
int x;
};
class B
{
public:
void print(int &s) { std::cout << s << std::endl; }
};
int main()
{
A obj(2);
B bObj;
bObj.print( obj.getPrivateDataBAD() );
return 0;
}
I'm having a bit of trouble with classes used within classes, from header files.
I have a class time in time.h:
#ifndef TIME_H
#define TIME_H
#include <iostream>
using namespace std;
class Time
{
private:
int hour, minute, second;
public:
Time();
~Time();
Time(int h, int m, int s);
int getHour();
int getMinute();
int getSecond();
void setHour(int hour);
void setMinute(int minute);
void setSecond(int second);
Time getTimeFromUser(Time b);
bool validTime(Time a);
void print24Hour(Time a);
void print12Hour(Time b);
};
#endif
Schedule.h
#ifndef SCHEDULE_H
#define SCHEDULE_H
#include <iostream>
#include "time.h"
using namespace std;
class Class
{
private:
string name;
int credits;
bool majorRequirement;
double avgGrade;
string days;
Time startTime;
Time endTime;
public:
Class();
~Class();
Class(string namae, int cred, bool majorReq, double avg, string day);
//Mutate
void setName(string h);
void setCredits(int c);
void setMajorRequirement(bool set);
void setAvgGrade(double g);
void setDays(string d);
void getStartTimeFromUser(Time b);
void getEndTimeFromUser(Time e);
// Access
string getName();
int getCredits();
bool getMajorRequirement();
double getAvgGrade();
string getDays();
Time& getStartTime();
Time& getEndTime();
};
#endif
Schedule.cpp:
Class::Class()
{
string name = "";
int credits = 0;
bool majorRequirement = false;
double avgGrade = 0.0;
string days = "";
}
Time::Time()
{
int hour = 0;
int minute = 0;
int second = 0;
}
Class::Class(string namae, int cred, bool majorReq, double avg, string day)
{
name = namae;
credits = cred;
majorRequirement = majorReq;
avgGrade = avg;
days = day;
}
Time::Time(int h, int m, int s)
{
second = s;
minute = m;
hour = h;
}
Time getTimeFromUser(Time b)
{
string time = "";
string hourS, minuteS, secondS = new string();
getline(cin,time);
hourS = time.substr(0,2);
minuteS = time.substr(3,2);
secondS = time.substr(6,2);
b.hour = atoi(hourS.c_str());
b.minute = atoi(minuteS.c_str());
b.second = atoi(secondS.c_str());
return b;
}
void getStartTimeFromUser(Time b)
{
startTime = getTimeFromUser(b);
}
void getEndTimeFromUser(Time e)
{
endTime = getTimeFromUser(e);
}
Other Mutators and Accessors here.
Main is long. Here is the severely condensed version:
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <iomanip>
#include "time.h"
#include "schedule.h"
using namespace std;
int main()
{
// Expecting that variables are properly declared
Class * klass = new Class[classcount];
cout << "Enter the start time for the class (format is HH:MM:SS): ";
klass[i].getStartTimeFromUser(classB);
cout << "Enter the end time for the class (format is HH:MM:SS): ";
klass[i].getEndTimeFromUser(classE);
for(int i = 0; i < classcount; i++)
{
// Data collected via getline and changed through mutators/accessors
// Problems arise when working with Time
klass[i].getStartTime().print24hour();
}
}
I get quite a few "hour, second, minute, etc." are private errors, I'm guessing I'm doing something simple in a rather wrong way. Please help.
I get a lot of this:
time.h:10:7: error: ‘int Time::hour’ is private
schedule.cpp:146:4: error: within this context
time.h:10:13: error: ‘int Time::minute’ is private
schedule.cpp:147:4: error: within this context
time.h:10:21: error: ‘int Time::second’ is private
schedule.cpp:148:4: error: within this context
schedule.cpp: In function ‘void getStartTimeFromUser(Time)’:
schedule.cpp:155:16: error: ‘setStartTime’ was not declared in this scope
schedule.cpp: In function ‘void getEndTimeFromUser(Time)’:
schedule.cpp:160:2: error: ‘endTime’ was not declared in this scope
time.h: In function ‘bool validTime(Time)’:
There are several errors in your code:
I assume class in your main() function represents an array of
Class; but this is illegal, since class is a C++ keyword.
You are trying to access a private member of a Class object
(class[i].startTime). This is illegal again. You would need a
public accessor to that data member:
You are calling a function that does not exist (print24()). If you
intended to call print24hour(), this function takes no parameters.
Putting it all together, you need to do three things:
Add an accessor for startTime in Class:
class Class
{
//...
public:
Time GetStartTime() {return startTime;}
};
Use a legal name for your array and use std::vector or std::array:
std::vector<Class> classArray;
// OR:
std::array<Class, SIZE> classArray;
Call the right methods correctly:
classArray[i].GetStartTime().print24hour();
I you want to access class[i].startTime.print24(getStartTime()) from main you need to make startTimepublic.
If this is good style is a different question.
You are trying to access the private members of a class using the object directly.
Please read about public and private access specifiers here.
class Class
{
private:
Time startTime;
public:
const Time & getStartTime(){
return startTime;
}
};
int main()
{
Class c;
c.getStartTime().print24Hour();
}
You want either that, or make startTime public.
Note the const; if you don't want the returned reference to be const, then make startTime public right now. You may think that making it private improves encapsulation; and yes, it does, as long as you don't provide read-write access to the variable, which happens if you don't mark the member function return type const.
If your printing function isn't marked const, then your const-correctness doesn't exist. If using const reference as return type here, then you have some things to fix.
Related reading: Pseudo-Classes and Quasi-Classes.