我最近拿起一本 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/