C ++如何使用来自另一个函数的调用来修改结构
C++ how to modify a struct using a call from another function
我正在尝试了解如何编写可以修改 struct
的函数。我想在我的 struct
日期中添加一天。但是,下面的 addOneDay
功能不起作用。
我的目标是addOneDay
到我的生日,使用函数。如何操作结构中的数据以使 addOneDay
起作用?
#include <iostream>
using namespace std;
struct Date
{
int year;
int month;
int day;
};
Date addOneDay(const Date& date);
Date addOneDay(const Date& date)
{
Date rdate = date.day+1; /* <- this doesn't work */
return rdate;
};
void assignValues(Date& myBirthday)
{
myBirthday.day = 27;
myBirthday.month = 1;
myBirthday.year = 1962;
}
main()
{
Date x;
assignValues(x);
cout << x.month << "/" << x.day << "/" << x.year << endl;
//addOneDay(x)
};
"How do I manipulate the data in the struct to get addOneDay to work?"
是不行的,因为你传递了一个const
引用参数,其实就是这个参数不能改。解决方案是实际使用 return
值
Date addOneDay(const Date& date);
Date addOneDay(const Date& date) {
Date rdate(date);
rdate.day = rdate.day + 1;
return rdate;
};
这一行是错误的。正如您所发现的。
Date rdate = date.day+1; /* <- this doesn't work */
因为您要将整数值分配给日期对象,而编译器目前不知道如何进行该转换。
您需要将值分配回 Date
的 day
字段 like
date.day += 1;
这失败了,因为日期是 const
。
如果您希望输入参数为 const
,那么您必须 return 一个新的 Date 对象。您传入的是const
,无法更改。
Date addOneDay(const Date& date)
{
Date d(date);
d.day = date.day + 1;
return d;
};
这会产生一些临时对象的成本。
如果您删除了 const
限制,您可以像这样使用相同的日期。
void addOneDay(Date& date)
{
date.day += 1;
};
我正在尝试了解如何编写可以修改 struct
的函数。我想在我的 struct
日期中添加一天。但是,下面的 addOneDay
功能不起作用。
我的目标是addOneDay
到我的生日,使用函数。如何操作结构中的数据以使 addOneDay
起作用?
#include <iostream>
using namespace std;
struct Date
{
int year;
int month;
int day;
};
Date addOneDay(const Date& date);
Date addOneDay(const Date& date)
{
Date rdate = date.day+1; /* <- this doesn't work */
return rdate;
};
void assignValues(Date& myBirthday)
{
myBirthday.day = 27;
myBirthday.month = 1;
myBirthday.year = 1962;
}
main()
{
Date x;
assignValues(x);
cout << x.month << "/" << x.day << "/" << x.year << endl;
//addOneDay(x)
};
"How do I manipulate the data in the struct to get addOneDay to work?"
是不行的,因为你传递了一个const
引用参数,其实就是这个参数不能改。解决方案是实际使用 return
值
Date addOneDay(const Date& date);
Date addOneDay(const Date& date) {
Date rdate(date);
rdate.day = rdate.day + 1;
return rdate;
};
这一行是错误的。正如您所发现的。
Date rdate = date.day+1; /* <- this doesn't work */
因为您要将整数值分配给日期对象,而编译器目前不知道如何进行该转换。
您需要将值分配回 Date
的 day
字段 like
date.day += 1;
这失败了,因为日期是 const
。
如果您希望输入参数为 const
,那么您必须 return 一个新的 Date 对象。您传入的是const
,无法更改。
Date addOneDay(const Date& date)
{
Date d(date);
d.day = date.day + 1;
return d;
};
这会产生一些临时对象的成本。
如果您删除了 const
限制,您可以像这样使用相同的日期。
void addOneDay(Date& date)
{
date.day += 1;
};