Using a vector and classes - c++

I have a problem that for you might look simple but I can't figure it out even though I really tried.
#include <iostream>
#include <string>
#include <vector>
//Functions Prototypes ---
void create_object(std::vector <Movie> &);
std::string set_name();
int set_ryear();
double set_rating();
//Classes ---
class Movie {
public:
std::string name;
int release_year;
double rating;
public:
//Constructors
Movie(std::string u_name, int u_release_year, double u_rating);
~Movie() {};
Movie(const Movie &);
};
//MAIN ---
int main() {
std::vector <Movie> Collection;
create_object(Collection);
return 0;
}
//Constructors ---
Movie::Movie(std::string u_name, int u_release_year, double u_rating)
:name{ u_name }, release_year{ u_release_year }, rating{ u_rating }{
}
//Stand-Alone Functions ---
char get_selection() {
char x;
std::cin >> x;
return x;
}
void create_object(std::vector <Movie> &x) {
std::string u_name = set_name();
int u_ryear = set_ryear();
double u_rating = set_rating();
Movie User_Movie{ u_name,u_ryear,u_rating };
}
std::string set_name() {
std::string x;
std::cout << "Name: ";
std::cin >> x;
return x;
}
int set_ryear() {
int x;
std::cout << "Release year: ";
std::cin >> x;
return x;
}
double set_rating() {
double x;
std::cout << "Rating: ";
std::cin >> x;
return x;
}
I'm just a beginner, so I don't know much, but for as much as I know classes should be types even if they are user-defined types, and they are supposed to give the possibility to be manipulated as primitive types.
So why, when I try to create a vector that expects a bunch of Movie types, or when I pass it by reference, I receive errors?
Error C2664 'void create_object(std::vector &)': cannot convert argument 1 from 'std::vector<Movie,std::allocator<Movie>>' to 'std::vector &'
Error C2923 'std::vector': 'Movie' is not a valid template type argument for parameter '_Ty'
Error C2065 'Movie': undeclared identifier
The main usage for it should be to be visible to all functions so that I can pass it to them as I want, and to make operations on its objects (like after creating a new object, I want to be able to add it into the collection using push_back() and all that stuff) after I create a menu system using switch.

You have not declared the Movie class by the time you reach this statement:
void create_object(std::vector <Movie> &);
The correct way to do C++ classes is to put the basic declaration in a separate file movie.h and then #include it in your code at the start.
If you cannot do that (although you really should), move the class declaration to the start of the file.

Related

Cannot display file(related to classes)

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.

C++ Using cin in member functions of a class

I am trying to use cin to read private members of a class within a member function of the class and i am getting an error [Error] no match for 'operator>>' in 'std::cin >> ((const Course*)this)->Course::courseID' ?
Is it possible to do that? Here is my code
//Course.h
#ifndef Course_H
#define Course_H
#include<string>
#include<iostream>
using namespace std;
class Course
{
private:
string courseID;
string courseName;
int credits;
Course * nextCourse;
public:
void EnterCourse() const;
void SetNext(Course *);
string GetCourseID() const;
string GetCourseName() const;
int GetCredits() const;
};
void Course::EnterCourse() const
{
cout<<"=======Enter Course Information========\n"
<<"Enter Course ID: \n";
cin>>courseID;
cout<<"Enter Course Name: \n";
cin>>courseName;
cout<<"Enter credits: \n";
cin>>credits;
}
string Course::GetCourseID() const
{
return courseID;
}
string Course::GetCourseName() const
{
return courseName;
}
int Course::GetCredits() const
{
return credits;
}
void Course::SetNext(Course * cou)
{
nextCourse=cou;
}
#endif
Using std::cin is considered writing to member data. But you can not change the data members using a const qualified member function. Remove the const specifier from the function declaration and definition if you want to achieve that functionality:
void Course::EnterCourse();
More info on the subject in these SO posts:
Meaning of “const” last in a C++ method declaration?
What is meant with “const” at end of function declaration?

Composition error in c++

Newbie to C++ over here. I am trying to create 2 classes and interlink them using Composition, but I keep getting errors.
#include <iostream>
#include <string>
using namespace std;
class student
{
public: int roll_no;
string name;
string dob;
void student_display()
{
cout<<roll_no<< " "<<name<<" "<<dob<<endl;
}
student(int roll,string names,string dateofb)
{
roll_no=roll;
name=names;
dob=dateofb;
}
~student(){};
};
class course
{
public:string course_name;
int duration;
void course_display()
{
cout<<course_name<< " "<<duration<<" "<<endl;
s1.student_display()<<endl;
}
course (string c_name,int dur,student s2):course_name(c_name),duration(dur),s1(s2){}
~course(){};
private : student s1;
};
class college
{
public: string college_name;
string location;
course c1;
course (string col_name,string loc,course c2):college_name(col_name),location(loc),c1(c2){}
~course(){};
};
int main() {
student s5(001,"Noel","28/04/1994");
s5.student_display();
course c1("Engineering",4,s5(001,"Noel","28/04/1994"));
c1.course_display();
return 0;
}
The errors are as follows:
prog.cpp: In member function 'void course::course_display()':
prog.cpp:32:35: error: invalid operands of types 'void' and '<unresolved overloaded function type>' to binary 'operator<<'
s1.student_display()<<endl;
^
prog.cpp: At global scope:
prog.cpp:45:20: error: expected ')' before 'col_name'
course (string col_name,string loc,course c2):college_name(col_name),location(loc),c1(c2){}
^
prog.cpp:47:13: error: declaration of '~course' as member of 'college'
~course(){};
^
prog.cpp: In function 'int main()':
prog.cpp:52:54: error: no match for call to '(student) (int, const char [5], const char [11])'
course c1("Engineering",4,s5(001,"Noel","28/04/1994"));
Could someone please help me out? I have tried going through forums with the same error but cant figure it out
^
I have modified the code as follows:
#include <iostream>
#include <string>
using namespace std;
class student
{
public: int roll_no;
string name;
string dob;
void student_display()
{
cout<<roll_no<< " "<<name<<" "<<dob<<endl;
}
student(int roll,string names,string dateofb)
{
roll_no=roll;
name=names;
dob=dateofb;
}
~student(){};
};
class course
{
public:
string course_name;
int duration;
private:
student s1;
public:
void course_display()
{
cout<<course_name<< " "<<duration<<" "<<endl;
s1.student_display();
}
course (string c_name,int dur,student s2):course_name(c_name),duration(dur),s1(s2){}
~course(){};
//private: // shifted before course_display()
// student s1;
};
// Not used
//class college
//{
//public:
// string college_name;
// string location;
// course c1;
//
// course (string col_name,string loc,course c2):college_name(col_name),location(loc),c1(c2){}
//
// //~course(){}; // destructor mismatch
//};
int main() {
student s5(001,"Noel","28/04/1994");
s5.student_display();
//course c1("Engineering",4,s5(001,"Noel","28/04/1994"));
course c1("Engineering",4,s5);
c1.course_display();
return 0;
}
and the output is follows:
Line 30: Remove the semicolon.
Line 45: Looks like copy/paste error, should be the constructor of the college class, right? Then change the name from course to college. Same for the destructor on the following line.
Line 52: You create the object s5 2 lines above, I guess you want to pass this object to the constructor of the course object. If so then just remove the expression in the brackets after s5.

vector wont push class function c++ [duplicate]

This question already has answers here:
Updating vector of class objects using push_back in various functions
(2 answers)
Closed 7 years ago.
I am attempting to make a text adventure sort of game, and I would like to avoid a bunch of conditionals, so I am trying to learn about the classes stuff and all that. I have created several classes, but the only ones that pertain to this problem are the Options class and the Items class. My problem is that I am trying to push_back() a object into a vector of the type of that object's class and it apparently doesn't happen yet runs until the vector is attempted to be accessed. This line is in main.cpp. I have researched on this, but I have not been able to find a direct answer, probably because I'm not experienced enough to not know the answer in the first place.
The program is separated into 3 files, main.cpp, class.h, and dec.cpp.
dec.cpp declares class objects and defines their attributes and all that.
main.cpp:
#include <iostream>
#include "class.h"
using namespace std;
#include <vector>
void Option::setinvent(string a, vector<Item> Inventory, Item d)
{
if (a == op1)
{
Inventory.push_back(d);
}
else {
cout << "blank";
}
return;
}
int main()
{
vector<Item> Inventory;
#include "dec.cpp"
Option hi;
hi.op1 = "K";
hi.op2 = "C";
hi.op3 = "L";
hi.mes1 = "Knife";
hi.mes2 = "Clock";
hi.mes3 = "Leopard!!";
string input1;
while (input1 != "quit")
{
cout << "Enter 'quit' at anytime to exit.";
cout << "You are in a world. It is weird. You see that there is a bed in the room you're in." << endl;
cout << "There is a [K]nife, [C]lock, and [L]eopard on the bed. Which will you take?" << endl;
cout << "What will you take: ";
cin >> input1;
hi.setinvent(input1, Inventory, Knife);
cout << Inventory[0].name;
cout << "test";
}
}
dec.cpp just declares the Item "Knife" and its attributes, I've tried pushing directly and it works, and the name displays.
class.h
#ifndef INVENTORY_H
#define INVENTORY_H
#include <vector>
class Item
{
public:
double damage;
double siz;
double speed;
std::string name;
};
class Player
{
public:
std::string name;
double health;
double damage;
double defense;
double mana;
};
class Monster
{
public:
double health;
double speed;
double damage;
std::string name;
};
class Room
{
public:
int x;
int y;
std::string item;
std::string type;
};
class Option
{
public:
std::string op1;
std::string op2;
std::string op3;
std::string mes1;
std::string mes2;
std::string mes3;
void setinvent(std::string a, std::vector<Item> c, Item d);
};
#endif
Any help would be greatly appreciated! I realize that the whole structure may need to be changed, but I think that this answer will help even if that may be the case.
My problem is that I am trying to push_back() a object into a vector of the type of that object's class and it apparently doesn't happen yet runs until the vector is attempted to be accessed.
it happen but only inside your setinvent method:
void Option::setinvent(string a, vector<Item> Inventory, Item d)
^^^^^^^^^^^^ - passed by value
Inventory is passed by value which means it is a local vector variable in setinvent function. If you want to modify vector from main function, make it a reference:
void Option::setinvent(string a, vector<Item>& Inventory, Item d)
^^^^^^^^^^^^ - passed by reference, modifies vector from main
now Inventory is local reference variable. Also dont forget to change setinvent declaration in header file.

Error In classes C++

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).