C++ - “_itoa”未在此范围内声明

C++ - ‘_itoa’ was not declared in this scope

在 UserProfile.h 中,我声明了 class UserProfile...

#include <iostream>
#include <map>
#include <string>

using namespace std;

class UserProfile
{
   ...
}

然后,我在 UserProfile.cpp

中定义了函数 UserProfile() 和 operator<<
#include "UserProfile.h"
#include <cstdlib>

inline UserProfile::UserProfile()
    : _login("guest"), _user_level(Beginner),
      _times_logged(1), _guesses(0), _correct_guesses(0)
{
    static int id = 0;
    char buffer[16];

    _itoa(id++, buffer, 10);
    _login += buffer;
}
...
ostream& operator<<(ostream &os, const UserProfile &rhs)
{
    os << rhs.login() << ' '
       << rhs.level() << ' '
       << rhs.login_count() << ' '
       << rhs.guess_count() << ' '
       << rhs.guess_correct() << ' '
       << rhs.guess_average() << endl;
    return os;
}

但是,当我尝试编译它们时,g++报错:

g++ UserProfile.cpp E44.cpp -o main
UserProfile.cpp: In constructor ‘UserProfile::UserProfile()’:
UserProfile.cpp:11:27: error: ‘_itoa’ was not declared in this scope
     _itoa(id++, buffer, 10);

但是我已经包含了"cstdlib"...好奇怪...

另外,当我想在主cpp中使用<<时,g++也报错:

#include "UserProfile.h"

int main()
{
    UserProfile anon;
    cout << anon;
    ...
}

g++ 报告:

E44.cpp: In function ‘int main()’:


E44.cpp:6:10: error: no match for ‘operator<<’ (operand types are ‘std::ostream {aka std::basic_ostream<char>}’ and ‘UserProfile’)
    cout << anon;

我很困惑...我做错了什么吗??

函数的正确名称是 itoa 而不是 _itoa。但是,它不能在 C++ 中使用。 cplusplus.com 说:

This function is not defined in ANSI-C and is not part of C++, but is supported by some compilers.

而是使用 std::to_string 或字符串流。

就 operator<< 的编译时错误而言,这是因为您在另一个翻译单元中定义运算符,而不是具有 main 函数的翻译单元,它将是我猜是单独编译的,你没有在头文件中声明它。为了使其工作,您需要声明重载运算符,最好在与 class' 头文件 UserProfile.h.[=13= 相同的头文件中]

ostream& operator<<(ostream &os, const UserProfile &rhs);

此外,您可能希望使其成为您 class 的 好友 以直接访问字段而不使用方法。这不会破坏封装,因为您同时实现了 class 和重载运算符。

class UserProfile
{
    friend ostream& operator<<(ostream &os, const UserProfile &rhs);
};