Reputation: 224
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 string
s?
Upvotes: 1
Views: 906
Reputation: 57179
You are returning a pointer to the str
member function rather than a string
. Call str()
for this to work
string Date::printIt()
{
...
return res.str();//call str method
}
Also you need to move the #include <string>
to the header file since string
is used for the return type of printIt
.
Upvotes: 1
Reputation: 258678
Your problem is with your include order:
#include "stdafx.h"
#include "Date.h"
#include <sstream>
#include <string>
You're including Date.h
, which contains string
, before you include the header that defines string
.
It should be
#include "stdafx.h"
#include <sstream>
#include <string>
#include "Date.h"
or better yet, include string
directly in the header. This is so you don't have to worry about the order in other cpp
files where you might include the header.
Upvotes: 3
Reputation: 1
Reorder you headers so that the string type declaration appears before Date.h
#include <sstream>
#include <string>
#include "stdafx.h"
#include "Date.h"
Upvotes: 0
Reputation: 182883
If Date.h
is going to use the string
class, then the necessary header files have to be included either before Date.h
or in Date.h
.
Upvotes: 5