类中的字符串// c++

Strings in classes // C++

本文关键字:c++ 字符串      更新时间:2023-10-16

我是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 s有问题?

如果Date.h要使用string类,那么必要的头文件必须包含 Date.h之前或 Date.h中。

您的问题在于您的include订单:

#include "stdafx.h"
#include "Date.h"
#include <sstream>
#include <string>

在包含定义string的头文件之前,先包含包含stringDate.h

应该是

#include "stdafx.h"
#include <sstream>
#include <string>
#include "Date.h"

或者更好的是,直接在标题中包含string。这样,您就不必担心其他cpp文件中可能包含头文件的顺序。

返回的是指向str成员函数的指针,而不是指向string的指针。调用str()使其工作

string Date::printIt()
{
    ...
    return res.str();//call str method
}

还需要将#include <string>移动到头文件中,因为string用于printIt的返回类型。

重新排序头文件,使字符串类型声明出现在Date.h之前

#include <sstream>
#include <string>
#include "stdafx.h"
#include "Date.h"