我是C ++的新手,并且在课程中遇到字符串
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
问题是printIt()
功能。 Visual Studio说声明是不兼容的。当我将函数类型更改为int
时,问题会消失,但为什么string
会出现问题?
答案 0 :(得分:5)
如果Date.h
将要使用string
类,则必须在 Date.h
之前或 in 中包含必要的头文件/ em> Date.h
。
答案 1 :(得分:3)
您的问题与您的包含订单有关:
#include "stdafx.h"
#include "Date.h"
#include <sstream>
#include <string>
在您添加定义Date.h
的标头之前,您要包含string
,其中包含string
。
应该是
#include "stdafx.h"
#include <sstream>
#include <string>
#include "Date.h"
或者更好的是,直接在标头中加入string
。这样您就不必担心可能包含标题的其他cpp
文件中的顺序。
答案 2 :(得分:1)
您正在返回指向str
成员函数的指针,而不是string
。请致电str()
以便此工作
string Date::printIt()
{
...
return res.str();//call str method
}
此外,您需要将#include <string>
移至头文件,因为string
用于返回类型printIt
。
答案 3 :(得分:0)
重新排序标题,以便字符串类型声明出现在Date.h
之前#include <sstream>
#include <string>
#include "stdafx.h"
#include "Date.h"