如何修复 C++ 中的"expected"错误

How to fix "expected" errors in c++

本文关键字:expected 错误 中的 何修复 C++      更新时间:2023-10-16

这是一个查找一个人年龄的程序。C++在第 33 行向我显示"预期"错误。错误是 calculate() 的函数定义。 你能帮我修复它吗?我不明白错误是什么。

#include<iostream.h>
#include<conio.h>
struct date
{
int day;
int month;
int year;
};
date birth;
date current;
void main()
{
void calculate(int,int,int,int,int,int);
cout<<"nEnter your date of birth";
cout<<"nDay: ";
cin>>birth.day;
cout<<"nMonth: ";
cin>>birth.month;
cout<<"nYear: ";
cin>>birth.year;
cout<<"nEnter current date";
cout<<"nDay: ";
cin>>current.day;
cout<<"nMonth: ";
cin>>current.month;
cout<<"nYear: ";
cin>>current.year;
calculate     (birth.day,birth.month,birth.year,current.day,current.month,current.year);
getch();
}
// Error on line below
void calculate(int birth.day,int birth.month,int birth.year,int   current.day,int current.month,int current.year)
{
int monthdays[]={31,28,31,30,31,30,31,31,30,31,30,31};
if(birth.day>current.day)
{
current.day=current.day=monthdays[birth.month-1];
current.month=current.month-1;
}
else if(birth.month>current.month)
{
current.year=current.year-1;
current.month=current.month+12;
}
int calculated_date=current.date-birth.date;
int calculated_month=current.month-birth.month;
int calculated_year=current.year=birth.year;
cout<<"Present age= "<<calculated_date<<calculated_month<<calculated_year;
}

(33,27) 中存在错误

C++不能将参数作为类的成员变量传递。在

void calculate(int birth.day, ...

birth.day无效。

但是,可以传递整个类,然后使用成员变量。

改变

void calculate(int,int,int,int,int,int);

void calculate(date, date); 

然后

calculate       (birth.day,birth.month,birth.year,current.day,current.month,current.year);

calculate(birth, current);

最后

void calculate(int birth.day,int birth.month,int birth.year,int   current.day,int current.month,int current.year)

void calculate(date birth, date current)

有很多方法可以改进这一点,通过参考传递

void calculate(const date & birth, date current) 

(请注意,current不是引用,因为它将在函数中修改)并清理calculate中的几个拼写错误

current.day=current.day=monthdays[birth.month-1]; 

应该是

current.day=current.day+monthdays[birth.month-1];

current.day+=monthdays[birth.month-1];

int calculated_date=current.date-birth.date;

应该更像

int calculated_day=current.day-birth.day;

编译器将捕获第二个拼写错误,但可能不会捕获第一个拼写错误。我也不相信calculate中使用的逻辑,但幸运的是,TurboC++ 附带了 Turbo 调试器,这是当时最好的调试器之一,在我看来,它仍然运行良好。

虽然很难在不看到错误的情况下判断错误的含义,并且很难将其行号与给定格式的发布代码相关联,但错误的最可能原因是 '." 不是标识符的有效字符,因此calculate函数定义中的所有参数名称都是无效标识符。这可能会导致包含单词"预期"(例如"预期的标识符")的错误消息。

如果必须单独传递所有参数名称,请考虑改用"_"或驼峰大小写作为参数名称。但是,您已经声明了这个方便的date结构进行传递,因此您可以让函数获取参数date birthdate current,而不是两个date实例中的每个成员。

错误可能来自第void calculate(int birth.day,int birth.month,int birth.year,int current.day,int current.month,int current.year)

只需将"."替换为"_"或类似包含在其正文中的内容

[编辑]

除了这一点,我鼓励你修改你的函数,只接收参数中的出生日期和当前日期,这是没有用的,提取它们的字段,而这可以由函数本身进行。

警告,因为您将电流修改为,因此您必须按值接收它,而您可以通过常量引用接收出生。当然,您也可以使用局部变量而不是修改当前...

相关文章: