为什么我不能在下面的代码中使用 `pos_type` 返回类型?

Bel*_*loc 1 c++ fstream visual-studio-2010

是VS2010中函数的定义basic_istream::tellg()。请注意,该函数返回类型为 的变量pos_typestreamoff但是,当我用 替换示例中使用的类型(如下所示)时pos_type,编译器会抱怨(C2065:'pos_type':未声明的标识符)。

pos_type定义在<fstream>as中typedef typename _Traits::pos_type pos_type;

// basic_istream_tellg.cpp
// compile with: /EHsc
#include <iostream>
#include <fstream>

int main()
{
    using namespace std;
    ifstream file;
    char c;
    streamoff i; // compiler complains if I replace streamoff by pos_type

    file.open("basic_istream_tellg.txt");
    i = file.tellg();
    file >> c;
    cout << c << " " << i << endl;

    i = file.tellg();
    file >> c;
    cout << c << " " << i << endl;
}
Run Code Online (Sandbox Code Playgroud)

Naw*_*waz 5

你不能pos_type没有资格就随便写。请注意,它是 的成员ifstream。所以你必须这样写:

ifstream::pos_type i; //ok
Run Code Online (Sandbox Code Playgroud)

现在应该可以了。

另外,由于using namespace std; 被认为是 bad,您应该避免它,而应该更喜欢使用完整的限定:

std::ifstream file;        //fully-qualified
std::ifstream::pos_type i; //fully-qualified
Run Code Online (Sandbox Code Playgroud)

在 C++11 中,您可以auto改为使用。

auto i = file.tellg();
Run Code Online (Sandbox Code Playgroud)

并让编译器推断istd::ifstream::pos_type

希望有帮助。