类构造函数打印有问题

时间:2017-06-14 21:00:53

标签: c++ class oop constructor

我正在尝试通过创建包含小时,分钟和秒的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;
}

4 个答案:

答案 0 :(得分:2)

  

我也不确定如何通过默认构造函数打印时间(0,0,0)。

除非我遗漏了一些微妙的东西,

// Construct a Time object using the default constructor.
Time time2;

// Print it's hour
std::cout << time2.getHour() << std::endl;

答案 1 :(得分:2)

对我来说很好,这是我的输出:

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;
}

只要您使用默认构造函数调用Time,就会调用此方法:

    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 . . .

答案 2 :(得分:0)

您共享的代码不会尝试打印使用默认构造函数构造的对象,因为getHour()会调用time1。正在做你告诉它要做的事情。如果您希望从time1获得全部时间,则必须致电所有获取者,例如:std::cout << time1.getHour() << " : " << time1.getMinute() << " : " << time1.getSecond() << std::endl

答案 3 :(得分:0)

&#34;我也不确定如何通过默认构造函数打印时间(0,0,0)。&#34;

考虑一个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;
}