C++不需要括号时期待括号?

C++ expecting parentheses when one isn't needed?

本文关键字:期待 C++ 不需要      更新时间:2023-10-16

我遇到了一个无法弄清楚的问题,我对 c++ 还很陌生。下面是一个代码片段:

#define secondsInHour 3600;          
#define secondsInMinute 60;
using namespace std;
int main()
{
    int totalSeconds;
    int convertedHours;
    int convertedMinutes;
    int convertedSeconds;
    cout << "Enter time in seconds: ";
    cin  >> totalSeconds;
    cout << endl;
    convertedHours = totalSeconds / secondsInHour;                          
    convertedMinutes = (totalSeconds - (convertedHours*secondsInHour))/secondsInMinute;             //D
    return 0;
}

当我尝试运行时,我收到以下错误:预期为")"谁能解释一下? 错误是指倒数第二行。

编辑:我正在使用Visual Studio 2015。 对不起,我引用了错误的行。 产生错误的行是"convertedMinutes = ...."

问题出在#define宏中的分号上。

当预处理器将宏的文本替换到代码中时,编译器看到的代码如下所示:

using namespace std;
int main()
{
int totalSeconds;
int convertedHours;
int convertedMinutes;
int convertedSeconds;
cout << "Enter time in seconds: ";
cin  >> totalSeconds;
cout << endl;
convertedHours = totalSeconds / 3600;;                          
convertedMinutes = (totalSeconds - (convertedHours*3600;))/60;;             //D
return 0;

看看secondsInHour宏中多余的分号是如何破坏convertedMinutes表达式的?

您需要删除分号:

#define secondsInHour 3600    
#define secondsInMinute 60

此代码:

#define secondsInHour 3600;          
#define secondsInMinute 60;

存在以下问题:

  • 在这种情况下,您根本不应该使用#define

  • 如果使用#define最好使用大写的宏名称以避免冲突

  • 如果您使用#define请不要将分号放在末尾

所以要么:

const int secondsInHour = 3600;          
const int secondsInMinute = 60;

#define secondsInHour 3600
#define secondsInMinute 60

甚至更好

#define SECONDS_IN_HOUR 3600
#define SECONDS_IN_MINUTE 60

但是首选第一个变体,因为它不会带来这样的意外惊喜