因此,我正在尝试制作一个程序,该程序需要一些随机输入的秒数并将其转换为“天,小时,分钟和秒”。我必须使用符号常量来定义一天中的小时,一小时中的分钟和一分钟中的秒。我将值传递了下来,但没有收到,因此我得到了一个巨大的负数。这是代码。如果有人能告诉我问题出在哪里,我将永远感激不已。

我在函数定义代码中使用了随机的代码来计算总秒数,以查看是否已接收到秒数。

#ifndef SECONDS_H_
#define SECONDS_H_

#define HOURS_IN_DAY 24
#define MINUTES_IN_HOUR 60
#define SECONDS_IN_MINUTES 60

#include <iostream>

using namespace std;

class Seconds
{
private:
    long totalSeconds;
public:
    Seconds();
    ~Seconds(){};
    Seconds(int totalSeconds);
    void Seconds::convertSeconds(int &days, int &hours, int &minutes, int &seconds);
};

#endif

...
#include <conio.h>
#include <string>
#include <iostream>
#include "seconds.h"

#define HOURS_IN_DAY 24
#define MINUTES_IN_HOUR 60
#define SECONDS_IN_MINUTE 60

Seconds::Seconds(int totalSeconds)
{
    totalSeconds = totalSeconds;
}

void Seconds::convertSeconds(int &days, int &hours, int &minutes, int &seconds)
{
    cout << endl;
    cout << "Total Seconds: " << totalSeconds;
    cout << endl;

    days = totalSeconds / MINUTES_IN_HOUR / SECONDS_IN_MINUTE / HOURS_IN_DAY;
    hours = (totalSeconds / MINUTES_IN_HOUR / SECONDS_IN_MINUTE) % HOURS_IN_DAY;
    minutes = (totalSeconds / MINUTES_IN_HOUR) % SECONDS_IN_MINUTE;
    seconds = (totalSeconds % SECONDS_IN_MINUTE);

}

...
#include <iostream>
#include <conio.h>
#include <string>
#include "seconds.h"

#define HOURS_IN_DAY 24
#define MINUTES_IN_HOUR 60
#define SECONDS_IN_MINUTES 60

using namespace std;

int main ()
{
    int totalSeconds;
    int days = 0, hours = 0, minutes = 0, seconds = 0;

    cout << "Enter a random massive amount of seconds: ";
    cin >> totalSeconds;

    Seconds sec(totalSeconds);

    sec.convertSeconds(days, hours, minutes, seconds);

    cout << "That is equivalent to " << days << " days, " << hours << " hours, " << minutes << " minutes, " << seconds << " seconds." << endl;

    cout << "Press any key to continue...";
    cin.sync();
    _getch();

    return 0;
}

最佳答案

这是个问题:

Seconds::Seconds(int totalSeconds)
{
    totalSeconds = totalSeconds;
}

函数参数totalSeconds遮蔽了类成员,因此此代码就像x = x;一样,它对this->totalSeconds无效。

要解决此问题,请使用其他变量名,或者最好使用构造函数初始化语法:
Seconds::Seconds(long totalSeconds)
   : totalSeconds(totalSeconds)
{
}

在此版本中,不会发生阴影,因为构造函数初始化列表很聪明。

关于c++ - 函数未接收到值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22902450/

10-11 15:31
查看更多