我的参数化构造函数说我的字符串变量未定义

My parameterized constructor says my string variable is undefined?

本文关键字:我的 变量 未定义 字符串 构造函数 参数      更新时间:2023-10-16

对不起,我很擅长编程,因此需要帮助,因此我可以继续执行其他任务。这是我下面的程序:

#include<iostream>
#include"date.h"
#include<string>
using namespace std;
int main()
{ 
    //string thurs;
    Date myDate(thurs,12,2014);
    cout<<"Day is: "<<myDate.getDay()<<endl;
    cout<<"month is: "<<myDate.getMonth()<<endl;
    cout<<"month is: "<<myDate.getYear()<<endl;
}

在哪里说"星期四",它说它是未申报的,我试图宣布它,但仍然没有解决我的问题,这是为什么我对此进行了评论。

这是我的班级,我不确定这是否是问题:

#include<iostream>
using namespace std;
class Date
{
    private:
        string day;
        int month;
        int year;
    public:
        Date(string day,int month,int year); //Param Constructor
        void setDay(string);
        void setMonth(int);
        void setYear(int);
        string getDay();
        int getMonth();
        int getYear();
};

最后是我的固定器/Geters,不确定这是否可能是问题:

#include"date.h"
Date::Date(string day,int month, int year)
{
    this->day=day;
    this->month=month;
    this->year=year;
}
//getters
string Date::getDay()
{
    return day;
}
int Date::getMonth()
{
    return month;
}
int Date::getYear()
{
    return year;
}

//Setters
void Date::setDay(string d)
{
    day=d;
}
void Date::setMonth(int m)
{
    month=m;
}
void Date::setYear(int y)
{
    year=y;
}

目前显示出" Thurs"以外的所有东西 - 任何帮助,对可怕的布局>&lt;

感到抱歉

在C 中,必须使用双引号"封装字符串文字,因此您可以做:

// Note "thurs" instead of thurs
Date myDate("thurs", 12, 2014);

也可以做:

string thurs = "thurs";         // Initialize a std::string with string literal "thurs"
Date myDate(thurs, 12, 2014);   // Pass std::string instance

作为旁注,当您要通过不便宜的参数(例如int,而是string and 时,您想制作本地副本,请考虑通过Value通过值和std::move(),例如:

Date::Date(string d, int m, int y)
        : day( std::move(d) )
        , month(m)
        , year(y)
{ }
void Date::setDay(string d)
{
    day = std::move(d);
}

还请注意,由于Getters不会修改Date的内部状态,因此您可能需要将它们标记为const

string Date::getDay() const
{
    return day;
}
int Date::getMonth() const
{
    return month;
}
int Date::getYear() const
{
    return year;
}

尝试

Date myDate("thurs",12,2014);

请注意,帕伦斯在这里有所不同 - 从变量名称更改为字符串。

您需要定义字符串变量,例如此string thurs("literal");

line

Date myDate(thurs,12,2014);

应该是

Date myDate("thurs",12,2014);

祝你好运!