以下C ++代码在编译时出错:
#include<iostream>
using namespace std;
class time
{
int hours;
int minutes;
public:
void gettime(int h, int m)
{ hours = h; minutes = m; }
void puttime(void)
{
cout << hours << " hours and ";
cout << minutes << " minutes " << "\n";
}
void sum(time, time);
};
void time::sum(time t1, time t2)
{
minutes = t1.minutes + t2.minutes;
hours = minutes/60;
minutes = minutes % 60;
hours = hours + t1.hours + t2.hours;
}
int main()
{
time T1, T2, T3; // LINE NUMBER 32.
T1.gettime(2, 45);
T2.gettime(3, 30);
T3.sum(T2, T2);
cout << "T1 = "; T1.puttime();
cout << "T2 = "; T2.puttime();
cout << "T3 = "; T3.puttime();
return 0;
}
以下错误,我得到了:
habeebperwad:~/study/cpp/eb$ g++ 5.7-objects-as-arguments.cpp
5.7-objects-as-arguments.cpp: In function ‘int main()’:
5.7-objects-as-arguments.cpp:32:7: error: expected ‘;’ before ‘T1’
5.7-objects-as-arguments.cpp:34:2: error: ‘T1’ was not declared in this scope
5.7-objects-as-arguments.cpp:35:2: error: ‘T2’ was not declared in this scope
5.7-objects-as-arguments.cpp:37:2: error: ‘T3’ was not declared in this scope
habeebperwad:~/study/cpp/eb$
如果我在语句'时间T1,T2,T3;'之前添加 class ,它可以正常工作。
为什么没有类不能正常工作?
答案 0 :(得分:15)
您的编译器定义std::time
,因此期望time(...);
或time;
。类名time
不明确,因此需要关键字class
。为防止这种情况,请勿使用using namespace std;
或重命名您的课程。
如果删除std::
,请不要忘记将命名空间限定符cout
添加到using namespace std;
。
我建议在g ++中启用所有编译器警告(-Wall -Wextra
)以防止此类错误,因为GCC暗示存在错误:
temp.cc:33:20:警告:表达式是函数的参考,而不是调用»时间«[ - Waddress] temp.cc:33:20:警告:表达式无效[-Wunused-value]