C++ 我的参数化构造函数说我的字符串变量未定义?
对不起,我的编程能力很差,需要帮助才能继续完成其他任务。 下面是我的程序:C++ 我的参数化构造函数说我的字符串变量未定义?,c++,C++,对不起,我的编程能力很差,需要帮助才能继续完成其他任务。 下面是我的程序: #include<iostream> #include"date.h" #include<string> using namespace std; int main() { //string thurs; Date myDate(thurs,12,2014); cout<<"Day is: "<<myDate.getDay()<<e
#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;
}
目前,它显示除“星期四”之外的所有内容-任何帮助和对糟糕布局的抱歉>试试看
请注意,paren在这里起到了很大的作用-将thurs从变量名更改为字符串。试试看
Date myDate("thurs",12,2014);
请注意,paren在这里起到了很大的作用-将thurs从变量名更改为字符串。您需要像下面这样定义字符串变量
字符串thurs(“literal”)代码>您需要像下面这样定义字符串变量stringthurs(“literal”)代码>行
Date myDate(thurs,12,2014);
应该是
Date myDate("thurs",12,2014);
祝你好运 线
Date myDate(thurs,12,2014);
应该是
Date myDate("thurs",12,2014);
祝你好运在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
或者你可以:
// 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 <代码>,但类似于“代码>字符串< /代码>”,并且您想制作本地副本时,考虑值的传递和<代码> STD::MOVER()/<代码>值,例如:
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);
}
还请注意,由于getter不修改日期的内部状态,因此您可能希望将其标记为常量
:
string Date::getDay() const
{
return day;
}
int Date::getMonth() const
{
return month;
}
int Date::getYear() const
{
return year;
}
<>在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
或者你可以:
// 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 <代码>,但类似于“代码>字符串< /代码>”,并且您想制作本地副本时,考虑值的传递和<代码> STD::MOVER()/<代码>值,例如:
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);
}
还请注意,由于getter不修改日期的内部状态,因此您可能希望将其标记为常量
:
string Date::getDay() const
{
return day;
}
int Date::getMonth() const
{
return month;
}
int Date::getYear() const
{
return year;
}
thurs
而不是“thurs”
?thurs
而不是“thurs”
?它起作用了!为这个愚蠢的问题感到抱歉-谢谢你=]它成功了!抱歉这个愚蠢的问题-谢谢=]他已经在使用名称空间std代码>,“变量”
实际上是一个常量。这实际上不是他的问题。我想,你至少应该将“变量”
更改为类似“文字”
的内容,以避免混淆;)好的,很抱歉造成混淆,我认为名称空间是一个细节,因为他可以单独理解它代码>,“变量”
实际上是一个常量。这实际上不是他的问题。我想,你至少应该将“变量”
更改为类似“文字”
的内容,以避免混淆;)好的,很抱歉给您带来了困惑,我认为名称空间是一个细节,因为他可以单独理解它。