I am new to C++ and troubling with strings in classes
Date.cpp:
#include "stdafx.h"
#include "Date.h"
#include <sstream>
#include <string>
using namespace std;
Date::Date(int day,int month,int year )
{
setDate(day,month,year);
}
void Date::setDate(int day,int month,int year)
{
this->day = day;
this->month = month;
this->year = year;
}
string Date::printIt()
{
std::stringstream res;
res<<this->day<<"/";
res<<this->month<<"/";
res<<this->year;
return res.str;
}
Date operator+(const Date &date,int day)
{
Date newDate(date.day,date.month,date.month);
newDate.day += day;
if(newDate.day > 30)
{
newDate.day%=30;
newDate.month+=1;
if(newDate.month>=12)
{
newDate.month%=30;
newDate.year+=1;
}
}
return newDate;
}
Date.h:
#ifndef DATE_H
#define DATE_H
using namespace std;
class Date
{
private:
int day,month,year;
Date(){}
public:
Date(int day,int month,int year);
void setDate(int day,int month,int year);
string printIt();
friend Date operator+(const Date &date, int day);
};
#endif
The problem is printIt() function. Visual Studio says that declarations are incompatible. When I change the type of function to int the problem disappears but why there is a problem with strings?
Your problem is with your include order:
You’re including
Date.h, which containsstring, before you include the header that definesstring.It should be
or better yet, include
stringdirectly in the header. This is so you don’t have to worry about the order in othercppfiles where you might include the header.