I have two classes (appointment, schedule), and a driver (main).
main.cpp:
#include <iostream>
#include "schedule.h"
#include "appointment.h"
using namespace std;
int main()
{
schedule mySch2("hello");
appointment myAppt(100002,"appointment",10,1,2013);
myAppt.printS(cout,2);
mySch2.addtoSchedule(myAppt);
system("PAUSE");
return EXIT_SUCCESS;
}
schedule.h
#ifndef SCHEDULE_H
#define SCHEDULE_H
#include<iostream>
#include "appointment.h"
using namespace::std;
const int SCH_ENTRIES = 10;
class schedule
{
public:
schedule(void);
schedule(const char *p);
bool addtoSchedule(const appointment &);
private:
char title[40];
int count;
appointment appointmentArray[SCH_ENTRIES];
};
#endif
schedule.cpp
#include "schedule.h"
#include "appointment.h"
#include <iostream>
using namespace::std;
schedule::schedule(void)
{
}
schedule::schedule(const char *p)
{
strcpy(title, p);
count = 0;
cout << title << endl;
cout << count << endl;
cout << "----" << endl;
}
bool schedule::addtoSchedule(const appointment & myAppt)
{
cout << appointmentArray[0].getDay();
return false;
}
appointment.h (I did not write this, this was provided) - not super important for this question
#ifndef APPOINTMENT_H
#define APPOINTMENT_H
#include <fstream>
#include <cstring>
using std::ostream;
// The Designer decides upon the following data and actions (i.e. Functions)
// and places the class in the file appointment.h
class appointment
{
public:
appointment(void); // default constructor
appointment(long, const char [],int d, int m, int y); // 5 argument constructor
appointment(const appointment &); // copy constructor
void keyBoardInput(void); // Assume no blanks in the desc
long getSource(void) const; // return source
void setSource(long); // change source
void setMonth(int);
void setDay(int);
void setYear(int);
int getMonth(void) const;
int getDay(void) const;
int getYear(void) const;
const char *getDescription(void) const; // return the address of the description
void changeDescription(const char *) ; // change an existing description
void copyTo(appointment &) const; // copy invoking instance to parameter
void incrementDate (void); // advance the date by ONE day
// You can assume 30 days in each month
void printS(ostream &, int dateFormat) const; // print all fields
// dateFormat == 1 month/day/year
// dateFormat == 2 day/month/year
~appointment(); // destructor - indicate the address
// of the variable that is leaving
private:
void setDescription(const char *); // used to allocated memory
// data
long source; // id of the person scheduling the appointment
char * desc; // description of the appointment - Dynamic Data
int day; // day, month, and year when the appointment
int month; // will happen
int year;
};
#endif
appointment.cpp (I did not write this, this was provided) - not super important for this question
#include "appointment.h"
#include <iostream>
using std::cin;
using std::cout;
appointment::appointment()
{
day = 0;
cout << "default appt\n";
}
appointment::appointment(long lSource, const char cDescription[], int d, int m, int y)
{
source = lSource;
day = d;
month = m;
year = y;
setDescription(cDescription);
}
appointment::appointment(const appointment & aToCopy)
{
source = aToCopy.getSource();
day = aToCopy.getDay();
month = aToCopy.getMonth();
year = aToCopy.getYear();
setDescription(aToCopy.getDescription());
}
void appointment::setDescription(const char * cSource)
{
if (desc != NULL) free (desc);
if (cSource == NULL)
return;
desc = (char *)malloc (strlen (cSource) + 1);
strcpy(desc, cSource);
}
long appointment::getSource(void) const
{
return source;
}
void appointment::setSource(long lSource)
{
source = lSource;
}
void appointment::setMonth(int iMonth)
{
month = iMonth;
}
void appointment::setDay(int iDay)
{
day = iDay;
}
void appointment::setYear(int iYear)
{
year = iYear;
}
int appointment::getMonth(void) const
{
return month;
}
int appointment::getDay(void) const
{
return day;
}
int appointment::getYear(void) const
{
return year;
}
//return the address of the description
const char * appointment::getDescription(void) const
{
return desc;
}
//change an existing description
void appointment::changeDescription(const char * cDescription)
{
setDescription(cDescription);
}
void appointment::copyTo(appointment &p) const
{
p.source = source;
p.day = day;
p.month = month;
p.year = year;
p.setDescription(desc);
}
void appointment::incrementDate(void)
{
int days;
switch (month)
{
case 1: // Jan: 31 Days
case 3: // Mar: 31 Days
case 5: // May: 31 Days
case 7: // Jul: 31 Days
case 10: // Oct: 31 Days
case 12: // Dec: 31 Days
days = 31;
break;
case 4: // Apr: 30
case 6: // Jun: 30
case 8: // Aug: 30
case 9: // Sep: 30
case 11: // Nov: 30
days = 30;
break;
case 2: // Feb: 28/29 Days (Depends on year modulus 4 a modulus 100).
days = !(year % 4) || !(year % 100) ? 29 : 28;
break;
}
day++;
if (day > days)
{
month++;
day = 1;
if (month > 12)
{
month = 1;
year++;
}
}
}
void appointment::printS(ostream &out, int dateFormat) const
{
if (dateFormat == 1)
{
out << month << "/" << day << "/" << year << "\n";
}
else if (dateFormat == 2)
{
out << day << "/" << month << "/" << year << "\n";
}
else
out << "Unsupported dateFormat parameter specified (should be 1 or 2).";
}
appointment::~appointment()
{
if (desc != NULL)
{
free (desc);
desc = NULL;
}
}
void appointment::keyBoardInput()
{
char temp[1024];
cout << "Please type the description: ";
cin.getline (temp, sizeof(temp) - 1, '\n');
cout << std::endl;
setDescription(temp);
}
My error occurs when the main driver calls mySch2.addtoSchedule(myAppt);
If I uncomment out the line inside of schedule appointmentArray[0].getDay() then everything runs and works fine with no segmentation error. As soon as that line gets uncommented, it throws the error during runtime (after a crash and I go into the debugger and step through the program).
You never initialize desc to nullptr for class appointment before invoking setDescription. This happens in both constructors. Learn to use an initializer list:
appointment::appointment()
: source(), desc(), day(), month(), year()
{
cout << "default appt\n";
}
appointment::appointment(long lSource, const char cDescription[], int d, int m, int y)
: source(lSource), desc(), day(d), month(m), year(y)
{
setDescription(cDescription);
}
appointment::appointment(const appointment & aToCopy)
: source(aToCopy.getSource())
, desc()
, day(aToCopy.getDay())
, month(aToCopy.getMonth())
, year(aToCopy.getYear())
{
setDescription(aToCopy.getDescription());
}
Why did it fault?
Without initialization the value in desc is indeterminate and therefore undefined behavior to dereference, and certainly so to pass to free.
void appointment::setDescription(const char * cSource)
{
if (desc != NULL) free (desc); // desc contains non-null garbage.
if (cSource == NULL)
return;
desc = (char *)malloc (strlen (cSource) + 1);
strcpy(desc, cSource);
}
That said, I would strongly encourage using a std::string instead. It would make the copy-consructor for this class completely disappear, and the default constructor trivial.
Comments about using malloc() in a C++ program reserved, as that opinion is all-but beat to death already on this forum (and I agree with te prevailing opinion).
Related
In main(), I am making an array myAppointments, and realize to make it work I would need to create a default constructor in Appointments.h, but when I do I get this error:
no matching function for call to 'Time::Time()'
Appointment(){
Here is Main:
/*
* Homework 4 -- UPDATE as needed
*/
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include "Appointment.h"
using namespace std;
void callPrint (Time &TimeOrApptObject) { TimeOrApptObject.print(); }
int main(){
int month, day, year, hour, minute,howLong;
Appointment myAppointments[19];
ifstream HW4DataFileHandle;
HW4DataFileHandle.open("Lab6Data.txt");
while (!HW4DataFileHandle.eof( )) {
for (int i = 1; i < 20; i++) {
HW4DataFileHandle>>month;
HW4DataFileHandle>>day;
HW4DataFileHandle>>year;
HW4DataFileHandle>>hour;
HW4DataFileHandle>>minute;
HW4DataFileHandle>>howLong;
myAppointments[i] = Appointment( month, day, year, hour, minute, howLong);
}
cout <<"enter a month" <<endl;
cin >> month;
cout <<"enter a day" <<endl;
cin >> day;
cout <<"enter a year"<<endl;
cin >> year;
Date myDate( month, day, year);
cout <<"Appointments for" << month <<"/" << day <<"/" << year <<":"<< endl;
for (int i = 0; i <13; i++){
if ( myAppointments[i]==Date myDate )
{
Time thisTime = myAppointments[i];
thisDate.print();
cout << endl;
}
}
}
And here are the header files:
Date.H
// Date.h -- Class Date UPDATE as needed
#ifndef DATE_H
#define DATE_H
class Date {
private:
int month;
int day;
int year;
public:
Date(int m, int d, int y) : month(m), day(d), year(y)
{
}
friend bool friendTorCompare2Dates (const Date&,const Date& );
};
bool friendTorCompare2Dates (const Date& Right, const Date& Left)
{
if (Right.month == Left.month && Right.day == Left.day )
return true;
else
return false;
}
#endif
Time.H
//Time.h -- Class Time UPDATE as needed
using namespace std;
#include<iostream>
#ifndef TIME_H
#define TIME_H
class Time {
private :
int hour; int minute;
public:
Time(int h, int m) : hour(h)
{
}
virtual void print() {
cout << hour << " " << minute <<" " ;
}
};
#endif
Appointment.h
// Appointment.h -- Class Appointment UPDATE as needed
//
using namespace std;
#include "Time.h"
#include "Date.h"
#ifndef APPOINTMENT_H
#define APPOINTMENT_H
class Appointment: public Date, public Time {
private:
int howLong;
public:
Appointment(int month, int day, int year, int hour, int minute, int howLong) :
Date(month, day, year), Time(hour, minute), howLong(howLong)
{
}
Appointment(){
month;
day;
year;
hour;
minute;
howLong;
}
};
#endif
What do I need to change in order to have my default constructor in Appointment work? If you notice any thing else, or have any other questions in regards to my question, please let me know. I would appreciate it if you would include an example in your answer.
This line:
Appointment myAppointments[19];
will call the default constructor of Appointment for each element.
Your default constructor doesn't explicitly call a constructor of Time, so the default constructor of Time will be called, which doesn't exist. Same with Date.
You can reinstate the default constructor like this:
class Time {
// ...
public:
Time() = default;
};
To get reasonable default behavior, you should provide default initial values for the members of your class, e.g.
class Time {
private :
int hour = 0;
int minute = 0;
public:
// ...
};
When you declare the array Appointment myAppointments[19];, the default constructor for Appointment is used immediately for all 19 elements. However, Date and Time do not have default constructors defined, but Appointment's default constructor will try to call them both implicitly, hence the error you are seeing since they don't exist.
So, you have 4 different ways to fix this:
make Appointment's default constructor call Date's and Time's non-default constructors explicitly (just like your other Appointment constructor does), passing in default values to them:
Appointment() :
Date(0, 0, 0), Time(0, 0), howLong(0)
{
}
give Date and Time their own default constructors, eg:
class Date {
private:
int month;
int day;
int year;
public:
Date() : month(0), day(0), year(0)
{
}
Date(int m, int d, int y) : month(m), day(d), year(y)
{
}
...
};
class Time {
private :
int hour;
int minute;
public:
Time() : hour(0), minute(0)
{
}
Time(int h, int m) : hour(h), minute(m)
{
}
...
};
Alternatively:
class Date {
private:
int month;
int day;
int year;
public:
Date(int m = 0, int d = 0, int y = 0) : month(m), day(d), year(y)
{
}
...
};
class Time {
private :
int hour;
int minute;
public:
Time(int h = 0, int m = 0) : hour(h), minute(m)
{
}
...
};
Alternatively (C++11 and later only):
class Date {
private:
int month = 0;
int day = 0;
int year = 0;
public:
Date() = default;
// or:
// Date() : Date(0, 0, 0) {}
Date(int m, int d, int y) : month(m), day(d), year(y)
{
}
...
};
class Time {
private :
int hour = 0;
int minute = 0;
public:
Time() = default;
// or:
// Time() : Time(0, 0) {}
Time(int h, int m) : hour(h), minute(m)
{
}
...
};
construct the array elements explicitly using placement-new so you can use Appointment's non-default constructor on them, eg:
typedef unsigned char AppointmentBuf[sizeof(Appointment)];
// better:
// #include <type_traits>
// using AppointmentBuf = std::aligned_storage<sizeof(Appointment), alignof(Appointment)>::type;
int main(){
AppointmentBuf myAppointments[19];
...
for (int i = 0; i < 19; i++) {
...
new (&myAppointments[i]) Appointment(month, day, year, hour, minute, howLong);
}
...
for (int i = 0; i < 19; i++) {
Appointment &appt = reinterpret_cast<Appointment&>(myAppointments[i]);
// use appt as needed...
}
...
// cleanup
for (int i = 0; i < 19; i++) {
reinterpret_cast<Appointment&>(myAppointments[i]).~Appointment();
}
return 0;
}
Change the array to hold Appointment* pointers, and then construct the array elements dynamically via new using Appointment's non-default constructor, eg:
int main(){
Appointment* myAppointments[19] = {};
...
for (int i = 0; i < 19; i++) {
...
myAppointments[i] = new Appointment(month, day, year, hour, minute, howLong);
}
...
for (int i = 0; i < 19; i++) {
// use myAppointments[i] as needed...
}
...
// cleanup
for (int i = 0; i < 19; i++) {
delete myAppointments[i];
}
return 0;
}
Alternatively (C++11 or later only):
#include <memory>
int main(){
std::unique_ptr<Appointment> myAppointments[19];
...
for (int i = 0; i < 19; i++) {
...
myAppointments[i] = std::make_unique<Appointment>(month, day, year, hour, minute, howLong);
}
...
for (int i = 0; i < 19; i++) {
// use myAppointments[i] as needed...
}
...
// no manual cleanup needed
return 0;
}
I am new to programming and an trying to create an array with a series of records in and then have the programme accept input and finally print out the contents of the list.
I am having trouble recording the values of some of the variables in my addRecord() function as the output of the code below is the following:
constructor called
-1:-1 Eat lunch
-1:-1 Watch TV
destructor called
Why am I missing the call to L1.addRecord(5, 30, "Make dinner"); completely and why aren't the times coming through (they are coming through as -1 which is set in the constructor)?
Thank you
#include <iostream>
#include <string>
using namespace std;
class Record {
private:
int hour;
int minute;
string todo;
public:
Record()
{
hour = -1;
minute = -1;
todo = "N/A";
}
void setData(int hour, int minute, const char* td);
void setData(Record& e);
void printRecord();
};
class List
{
private:
Record* recordArr;
int maxRecords;
int actualRecordCount;
public:
List(int maxRecords);
List(List& s) {
actualRecordCount = s.actualRecordCount;
maxRecords = s.maxRecords;
recordArr = new Record[maxRecords];
for (int i = 0; i < actualRecordCount; i++)
{
recordArr[i].setData(s.recordArr[i]);
}
std::cout << "copy constructor called." << std::endl;
}
~List();
bool addRecord(int hour, int minute, const char* todo);
void printList();
};
///////////////////////////
void Record::setData(int hour, int minute, const char* td)
{
hour = hour;
minute = minute;
todo = td;
}
void Record::setData(Record& e)
{
hour = e.hour;
minute = e.minute;
todo = e.todo;
}
void Record::printRecord()
{
std::cout << hour << ":" << minute << " " << todo << std::endl;
}
List::List(int maxRecords)
: maxRecords(maxRecords)
{
actualRecordCount = 0;
recordArr = new Record[maxRecords];
std::cout << "constructor called" << std::endl;
}
List::~List()
{
std::cout << "\ndestructor called";
delete[] recordArr;
}
bool List::addRecord(int hour, int minute, const char* todo)
{
Record newRecord; // create new Record
newRecord.setData(hour, minute, todo); //assign values
if (actualRecordCount >= maxRecords) // array full
{
return false;
}
else
{
recordArr[actualRecordCount] = newRecord; // put new Record into the array of Entry
actualRecordCount++; // increment Entry count
return true;
}
}
void List::printList()
{
for (int i = 0; i < actualRecordCount; i++)
{
recordArr[i].printRecord();
cout << endl;
i++;
}
}
int main() {
List L1(20);
L1.addRecord(2, 30, "Eat lunch");
L1.addRecord(5, 30, "Make dinner");
L1.addRecord(7, 30, "Watch TV");
L1.printList();
}
void Record::setData(int hour, int minute, const char* td)
{
hour = hour;
"hour" is the name of a parameter to this setData() method. hour=hour;, therefore, sets this parameter to itself. This accomplishes absolutely nothing, whatsoever. Same for other two assignments that follow.
Your obvious intent here is to initialize the class that happens to have members with the same name. When different things have the same name in C++ there's a complicated set of rules that choose which "thing" the name represents. These rules are the same on the left and the right side of the = operator, so both of these hours end up referring to the same object: the parameter to this class method.
You can simply rename the parameters to the method:
void Record::setData(int hourArg, int minuteArg, const char* tdArg)
{
hour = hourArg;
and so on. Or, if you wish to keep the parameter names the same, make things more explicit:
this->hour=hour;
The other error is here
void List::printList()
{
for (int i = 0; i < actualRecordCount; i++)
{
recordArr[i].printRecord();
cout << endl;
i++;
}
}
You have i++ twice.
One problem is that your Record::setData function with three arguments doesn't actually set the hour and minute fields of the class object! This is caused by your use of arguments with the same name as the class members, which (IMHO) is bad coding style. So, in the following code, your first two assignments just replace the argument values with themselves:
void Record::setData(int hour, int minute, const char* td)
{
hour = hour; // This and the following line are self-assignments to the arguments
minute = minute; // given and, as such, are effectively doing nothing!
todo = td; // This, however, is OK, because there is no ambiguity.
}
To fix this, either add an explicit this-> reference to the targets:
void Record::setData(int hour, int minute, const char* td)
{
this->hour = hour;
this->minute = minute;
todo = td;
}
Or (much better, in my opinion) give the first two arguments non-ambiguous names:
void Record::setData(int in_hour, int in_minute, const char* td)
{
hour = in_hour;
minute = in_minute;
todo = td;
}
So made a class called ‘Item’, and the object of that class will have a 100% condition at the start, the Player stores items (with name “apple” in this case) whenever I tell him to. In the degradeT function I want to pass the whole vector containing the items that the player has picked up by far and then change the condition of each Item in that vector by -1 through the chCond function.
first error:
initial value of reference to non-const must be an lvalue
second error:
'void degradeT(std::vector<Item,std::allocator<_Ty>> &)': cannot convert argument 1 from 'std::vector<Item,std::allocator<_Ty>>' to 'std::vector<Item,std::allocator<_Ty>> &'
#include "pch.h"
#include <iostream>
#include <string>
#include <vector>
using std::cout; using std::cin; using std::endl;
using std::string; using std::vector; using std::to_string;
class Item {
private:
string name; // Item name
float condition; // Item condition
bool consumable; // Is the item consumable
public:
Item() {}
Item(string a, float b, bool c) { name = a; condition = b; consumable = c; }
Item(string a, bool c) { name = a; condition = 100.f; consumable = c; }
string getName() {
return name;
}
float getCond() {
return condition;
}
bool isCons() {
return consumable;
}
void chCond(float a) { // Change Item condition
condition += a;
}
};
//-----------------------
class Player {
private:
vector<Item> plItems; // Item container
public:
Player() {}
void pickUpItem(Item a) { // Adding Items to inventory
plItems.push_back(a);
cout << a.getName() << " added to inventory!\n";
}
void checkItemConds() { // Checking condition of all items
for (unsigned int a = 0, siz = plItems.size(); a < siz; a++) {
cout << plItems[a].getName() << "'s condition is: " << plItems[a].getCond() << "%\n";
}
}
Item returnItem(unsigned int a) { // Return a specific Item
return plItems[a];
}
int getCurInvOcc() { // Get cuurent inventory occupation
return plItems.size();
}
vector<Item> getPlItems() { // Return the vector (Item container)
return plItems;
}
};
//-------------------------
void degradeT(vector<Item>& Itemss); // Degrade item after some time
//-------------------------
int main()
{
Player me; // me
string inp; // input
int num = 1; // apple 1, apple 2, apple 3...
while (inp != "exit") {
cin >> inp;
if (inp == "addApple") {
Item apple(("apple " + to_string(num)), true);
me.pickUpItem(apple);
num++;
}
if (inp == "checkItemConds") {
me.checkItemConds();
}
if (inp == "timeTick") {
// This doesn't have anything to do with time I just want to test the function manually
degradeT(me.getPlItems());
}
}
system("PAUSE");
return 0;
}
void degradeT(vector<Item> &Itemss) {
for (unsigned int a = 0, siz = Itemss.size(); a < siz; a++) {
Itemss[a].chCond(-1);
cout << Itemss[a].getName() << endl;
}
}
I'm not sure what your question is, but your error is related to the function void degradeT(vector<Item> & Itemss).
This functions expects a reference but you are passing an r-value. You can either return a reference with getPlItems() or pass an l-value to degradeT.
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.
I have some trouble figuring out a few things. Basically I have 2 classes, and whenever I create the objects, it works completely fine. However when I try to push_back to a vector in main() function, it return 0 0 0 (B default values), and if I try to make a void function, which would do this, it gives back segmentation fault. Any ideas?
class Date
{
public:
Date(int day=0, int month=0, int year=0) : _day(day), _month(month),_year(year) {}
int get_day() { return _day; }
int get_month() { return _month; }
int get_year() { return _year; }
void writestuff() { std::cout << _day << "/" << _month << "/" << _year<< std::endl; }
~Date(){}
private:
int _day;
int _month;
int _year;
};
class Adatok
{
public:
Adatok(std::string name, std::string path, Date date ): _name(name), _path(path), _date(date) {}
void writestuff()
{
std::cout<<_name<<" "<<_path<<" ";
_date.writestuff();
std::cout<<std::endl;
}
Adatok(const Adatok& other){}
Adatok operator= (const Adatok& other){}
~Adatok(){}
private:
std::string _name;
std::string _path;
Date _date;
};
void database(std::string& temp, std::vector<Adatok> my_vec); // this would be the segmentation fault code, it's not implemented anymore
int main(int argc, char **argv)
{
std::vector<Adatok> my_vec;
std::string temp;
boost::filesystem::ifstream input_file("input");
while (getline(input_file, temp))
{
//---------------------------------don't mind theese------------------------------------------------------------------
temp += ',';
std::string name = temp.substr(temp.find_first_of('"'),temp.find_first_of(','));
temp.erase(0, name.length() + 1);
std::string path = temp.substr(temp.find_first_of('"'),temp.find_first_of(','));
temp.erase(0, path.length() + 1);
std::string numbers(temp.substr(temp.find_first_of('"') + 1,temp.find_first_of('-')));
int year, month, day;
year = std::atoi(numbers.c_str());
temp.erase(0, temp.find_first_of('-') + 1);
numbers = temp.substr(0, temp.find_first_of('-'));
month = std::atoi(numbers.c_str());
temp.erase(0, temp.find_first_of('-') + 1);
numbers = temp.substr(0, temp.find_first_of(' '));
day = std::atoi(numbers.c_str());
//Date obj(day, month, year);
//Adatok elem(name, path, obj);
//---------------------------------------don't mind theese-----------------------------------------------------------------
my_vec.push_back(Adatok(name,path,Date(day,month,year))); //probably fails
}
for(std::vector<Adatok>::iterator it{my_vec.begin()};it !=my_vec.end();it++)
it -> writestuff();
return 0;
}
"however when i try to push_back to a vector in MAIN function, it
return 0 0 0 (B default values)"
This is because of not initializing the member variables of B class. This should be done when you push_back the a new A object to the std::vector like follows:
vecA.push_back(A("name", "path", B(15, 04, 2018)));
If your doubt is how to to use push_back is, above will certainly clarified it.
Update: I have set the copy constructor and copy assignment operator to default and it worked. Live action: https://www.ideone.com/TlmAm2
#include <iostream>
#include <string>
#include <vector>
class Date
{
public:
Date(int day = 0, int month = 0, int year = 0)
: _day(day), _month(month),_year(year) {}
~Date(){}
int get_day() { return _day; }
int get_month() { return _month; }
int get_year() { return _year; }
void writestuff()
{
std::cout << _day << "/" << _month << "/" << _year<< std::endl;
}
private:
int _day;
int _month;
int _year;
};
class Adatok
{
public:
Adatok(std::string name, std::string path, Date date )
: _name(name), _path(path), _date(date) {}
~Adatok(){}
void writestuff()
{
std::cout<<_name<<" "<<_path<<" ";
_date.writestuff();
std::cout<<std::endl;
}
//change in copy constructor and copy assignment operator
Adatok(const Adatok& other) = default;
Adatok& operator= (const Adatok& other) = default;
private:
std::string _name;
std::string _path;
Date _date;
};
void database(std::string temp, std::vector<Adatok> my_vec)
{
for(auto& it: my_vec)
it.writestuff();
}
int main(int argc, char **argv)
{
std::vector<Adatok> my_vec;
int year = 2018, month = 04, day = 15;
std::string name = "name1", path = "path1";
my_vec.push_back(Adatok(name,path,Date(day,month,year)));
database("something", my_vec);
return 0;
}