遇到与类构造函数打印
我想通过创建一个包含小时,分钟和秒的Time类来了解类和它们的构造函数是如何工作的。我想通过使用默认构造函数打印一次,并通过用户输入打印一次。当我的程序编译时,它并不要求用户输入,很可能是因为我调用类函数getHour(如果我只打印输入小时)。我也不确定如何通过默认构造函数打印时间(0,0,0)。遇到与类构造函数打印
任何帮助,将不胜感激!
主营:
#include <iostream>
#include "Time.h"
int main(){
std::cout << "Enter the hour, minute, and second: " << std::endl;
int hour, minute, second;
std::cin >> hour >> minute >> second;
Time time1(hour, minute, second);
std::cout << time1.getHour() << std::endl;
return 0;
}
类实现:
#include <iostream>
#include "Time.h"
//default constructor
Time::Time() {
hour = 0;
minute = 0;
second = 0;
}
//construct from hour, minute, second
Time::Time(int theHour, int theMinute, int theSecond) {
hour = theHour;
minute = theMinute;
second = theSecond;
}
int Time::getHour() const {
return hour;
}
int Time::getMinute() const {
return minute;
}
int Time::getSecond() const {
return second;
}
正常工作对我来说,这是我的输出:
Enter the hour, minute, and second:
2
45
32
2
Press any key to continue . . .
确保正在重建的代码并运行新的可执行文件。
在构造函数中,你可以这样做:
Time::Time() {
hour = 0;
minute = 0;
second = 0;
std::cout << hour << " " << minute << " " << second << std::endl;
}
将其称为随时调用时使用默认的构造函数:
std::cout << "Enter the hour, minute, and second: " << std::endl;
int hour, minute, second;
std::cin >> hour >> minute >> second;
Time t; //<--- this prints 0,0,0
Time time1(hour, minute, second);
std::cout << time1.getHour() << std::endl;
system("pause");
return 0;
将导致:
Enter the hour, minute, and second:
11
19
59
0 0 0
11
Press any key to continue . . .
谢谢,我现在明白了! – Mariankka
我也不清楚如何通过默认的构造函数打印时间(0,0,0)。
除非我失去了一些东西微妙,
// Construct a Time object using the default constructor.
Time time2;
// Print it's hour
std::cout << time2.getHour() << std::endl;
我想问题是这个+运行一个旧的可执行文件。 – drescherjm
编译时,它仍然不会打印任何内容。 – Mariankka
@Mariankka,你的编程环境是什么?你如何运行该程序? –
您共享的代码不会尝试打印自以来使用默认构造函数构造的对象由time1
调用。正在做你告诉它做的事。如果从time1
要充分时间,你就必须调用所有的干将例如:std::cout << time1.getHour() << " : " << time1.getMinute() << " : " << time1.getSecond() << std::endl
“我也不清楚如何通过默认的构造函数打印时间(0,0,0)。 “
考虑displayTime()
方法,可以叫上显示任何实例
int _tmain(int argc, _TCHAR* argv[])
{
std::cout << "Enter the hour, minute, and second: " << std::endl;
int hour, minute, second;
std::cin >> hour >> minute >> second;
Time time1(hour, minute, second); // overloaded constructor
Time time2; // default constructor
// std::cout << time1.getHour() << std::endl;
// std::cout << time2.getHour() << std::endl;
time1.displayTime();
time2.displayTime();
getch();
return 0;
}
添加displayTime的时间()方法
void Time::displayTime() const{
std::cout << this->hour << ","
<< this->minute << ","
<< this->second << std::endl;
}
@drescherjm感谢您的编辑。 – dmaelect
***它不要求用户输入,最有可能是因为我调用类函数getHour(如果我只打印输入小时)***您确定您正在运行当前代码的构建?输入在'main()'中,并且与'getHour()'无关' – drescherjm