c++ - Book Not Compiling 中的示例(时间函数)

标签 c++ time

我最近拿起一本 c++ 书,“C++ 编程的完整指南”,但我似乎无法找到正确编译的示例。我想这是一个版本问题,但我似乎找不到任何关于这个版本的“时间”功能的任何信息。

“时间”函数的用法最近有变化吗?

#include <iostream>
#include <string>
#include <iomanip>
#include <cctype>
#include <ctime>

using namespace std;

long timediff(void);
static string secret = "ISUS";
static long maxcount = 3, maxtime = 60;

bool getPassword()
{
    bool ok_flag = false;
    string word;
    int count = 0, time = 0;
    timediff();
    while (ok_flag != true && ++count <= maxcount)
    {
        cout << "\n\nInput the password: ";
        cin.sync();
        cin >> setw(20) >> word;
        time += timediff();
        if (time >= maxtime)
            break;
        if (word != secret)
            cout << "Invalid password!" << endl;
        else
            ok_flag = true;
    }
    return ok_flag;
}

long timediff()
{
    static long sec = 0;
    long oldsec = sec;
    time( &sec);
    return (sec - oldsec);
}

构建时出现以下错误...

1>d:\c++ training\learning\learning\source.cpp(39): error C2664: 'time_t time(time_t *const )': cannot convert argument 1 from 'long *' to 'time_t *const '
1>d:\c++ training\learning\learning\source.cpp(39): note: Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast
1>Done building project "Learning.vcxproj" -- FAILED.

最佳答案

std::time的签名是

std::time_t time( std::time_t* arg );

在哪里std::time_t定义为:

typedef /* unspecified */ time_t;

本书假定long 是未指定的类型。这对任何程序员来说都是一个糟糕的教训。而且您正在以艰难的方式学习它,因为 typedef 发生了变化,但代码示例没有。

像这样的类型别名的全部意义在于抽象实现细节。并允许您编写可移植代码。书中关于别名的假设是没有根据的。并且表明作者不应该教任何人 C++。

关于c++ - Book Not Compiling 中的示例(时间函数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48152028/

相关文章:

C++代码格式化

python - Python cProfile 中的严重开销?

c++ - 在 C++11 中获取当前时间的最快方法是什么?

c - 使用 Contiki 测量时间(以时钟滴答为单位)

c++ - VTK:在每个模拟时间步更新 renderWindow 中的数据点

c++ - 从 swig 返回 double * 作为 python 列表

c++ - 如何在传递给 C/C++ 宏之前解析 int 变量?

c++ - 使用 ALSA 的函数 snd_pcm_writei 我可以立即释放样本缓冲区吗?

c++ - 无法从 '_int64' 转换为 'Data *'

go - 如何使用go获取两位数的当前小时和分钟?