C++不需要括号时期待括号?
C++ expecting parentheses when one isn't needed?
我遇到了一个无法弄清楚的问题,我对 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
但是首选第一个变体,因为它不会带来这样的意外惊喜
相关文章:
- 违反const正确性:我应该现实地期待什么问题
- C++不需要括号时期待括号?
- 期待一个表达式
- 在期待"const char"的同时获得"char"
- GoogleMock:期待两个方法调用中的任何一个
- 在不需要主表达式时" / "之前期待一个主要表达式
- 我可以从双精度中期待什么精度
- 期待来自另一个线程的谷歌模拟调用
- Boost.Spirit with Boost.Variant 和 C++11:期待一个零参数构造函数
- 当我使用本征密集矩阵数据结构时,我应该期待什么
- runtime_error期待";"?
- 为什么要编译?期待"cannot assign a constant to a non-const reference"
- 期待一个表达,一个新手的错误
- 我怎么能反复期待接二连三的电话