#include <iostream>
using namespace std;
class time
{
private:
int hour;
int min;
int sec;
public:
void get_time(int h,int m,int s)
{
hour = h;
min = m;
sec = s;
}
void show_time()
{
cout << "The time is: " << hour << "hours " << min << "minutes " << sec << "seconds";
}
};
int main()
{
time t1;
t1.get_time(5, 4, 2);
t1.show_time();
return 0;
}
output:
time.cpp: In function ‘int main()’:
time.cpp:25:7: error: expected ‘;’ before ‘t1’
time t1;
^
time.cpp:28:2: error: ‘t1’ was not declared in this scope
t1.get_time(5, 4, 2);
^
答案 0 :(得分:2)
有一个名为time
的全局函数,继承自C标准库。它隐藏了你的类名,[basic.scope.declarative] / 4:
在单个声明性区域中给出一组声明,每个声明 它指定相同的非限定名称,
[..]
正好一个声明应声明一个不是typedef名称的类名或枚举名 [......]所有其他声明均指函数 和功能模板; 在这种情况下隐藏类名或枚举名称(3.3.10)。 [..]
最简单的解决方案是为您的类提供另一个名称(例如Time
- C和C ++标准库从不在标识符中使用大写字母。)
答案 1 :(得分:1)
我的编译器提供了一些非常有用的诊断信息,可以准确地解释发生了什么:
$ g++ test.cpp
test.cpp:25:6: error: must use 'class' tag to refer to type 'time' in this scope
time t1;
^
class
/usr/include/time.h:118:8: note: class 'time' is hidden by a non-type
declaration of 'time' here
time_t time(time_t *);
^
1 error generated.
我认为最好的策略是给你的班级一个不同的名字(或许Time
大写T
?)