You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

C++书籍示例编译失败:time函数参数类型不匹配问题求助

问题分析与解决方案

首先,你的编译错误完全是类型不匹配导致的,和time()函数的用法变更无关——这个函数的标准接口多年来没有变化。

错误原因

time()函数的标准签名是:

time_t time(time_t* arg);

它接受的参数是time_t*类型的指针,但你的代码里把sec定义成了long类型,传递&sec时就会出现long*time_t*的类型不兼容错误。

time_t是C/C++标准库定义的时间存储专用类型,虽然它通常在底层是整数类型(比如longlong long),但标准并没有强制它必须等于long。直接用long替代time_t是不标准的写法,在不同编译器/平台上可能会出问题,这就是你现在遇到的情况。

修正后的代码

把所有涉及时间存储的变量类型从long改成time_t即可解决问题:

#include <iostream>
#include <string>
#include <iomanip>
#include <cctype>
#include <ctime>
using namespace std;

time_t timediff(void); // 修改返回值类型为time_t
static string secret = "ISUS";
static long maxcount = 3, maxtime = 60;

bool getPassword() {
    bool ok_flag = false;
    string word;
    int count = 0;
    time_t time = 0; // 这里也改成time_t
    timediff();
    while (!ok_flag && ++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;
}

time_t timediff() {
    static time_t sec = 0; // 把long改成time_t
    time_t oldsec = sec;
    time(&sec); // 现在参数类型匹配了
    return (sec - oldsec);
}

额外建议

如果你用的是C++11及以上版本,更推荐使用<chrono>库来处理时间,它的类型安全更好,比如:

#include <chrono>

// 替代timediff的写法
auto timediff() {
    static auto last = std::chrono::steady_clock::now();
    auto now = std::chrono::steady_clock::now();
    auto diff = std::chrono::duration_cast<std::chrono::seconds>(now - last).count();
    last = now;
    return diff;
}

这种写法完全避免了time_t的类型依赖,更符合现代C++的风格。

内容的提问来源于stack exchange,提问作者Alex Harris

火山引擎 最新活动