这个班级,特别是粗体的行让我感到困惑。为什么我们要两次提到时间?如果删除第一个粗线,会发生什么?
time.h中
class Time {
public:
Time(); // this is "the first bold line"
Time(int h, int m, int s); // this is another "lines in bold"
void set(int h, int m, int s);
void print();
int allSeconds();
void difference(Time t);
int getHour();
int getMinute();
int getSecond();
void setHour(int h);
void setMinute(int m);
void setSecond(int s);
private:
int hour, minute, second;
};
答案 0 :(得分:1)
Time();
是默认构造函数的声明。在遇到类似Time t;
的内容时调用它。
由于提供了额外的构造函数Time(int h, int m, int s);
,编译器不会自动生成默认构造函数。
您可以通过编写Time() = default;
告诉编译器采用编译器生成的默认构造函数。或者,为3参数构造函数提供默认参数:然后它可以代表默认参数。
C ++标准库的某些部分(尤其是容器)要求对象是默认构造的。因此,如果您错过了,那么根据您的课程使用情况,您可能会遇到一些编译错误。
答案 1 :(得分:0)
如果'粗线'将被删除,类Time
将没有无参数构造函数。编译器不会生成一个,因为定义了非参数构造函数。实际效果取决于整个实现的任何部分是否使用无参数构造函数。
'粗线'不是重复;实际上,声明了两个具有不同签名的不同构造函数。
答案 2 :(得分:0)
他们不是阶级定义,他们是建构者。如果使用以下代码删除第一个(即default constructor),您会看到会发生什么。
int main() {
Time time1; // 1st (default) constructor called
Time time2(12, 0, 0); // 2nd constructor called
return 0;
}