C++ 为什么可以';我不能在下面的代码中使用'pos_type'返回类型吗?

C++ 为什么可以';我不能在下面的代码中使用'pos_type'返回类型吗?,c++,visual-studio-2010,fstream,C++,Visual Studio 2010,Fstream,是VS2010中函数basic\u istream::tellg()的定义。请注意,该函数返回类型为pos\u type的变量。但是,当我将下面给出的示例中使用的类型streamoff替换为pos\u type时,编译器会抱怨(C2065:“pos\u type”:未声明的标识符) pos\u type在中定义为typedef typename\u Traits::pos\u type pos\u type // basic_istream_tellg.cpp // compile with:

是VS2010中函数
basic\u istream::tellg()
的定义。请注意,该函数返回类型为
pos\u type
的变量。但是,当我将下面给出的示例中使用的类型
streamoff
替换为
pos\u type
时,编译器会抱怨(C2065:“pos\u type”:未声明的标识符)

pos\u type
中定义为
typedef typename\u Traits::pos\u type pos\u 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;
}
//basic\u istream\u tellg.cpp
//使用:/EHsc编译
#包括
#包括
int main()
{
使用名称空间std;
ifstream文件;
字符c;
streamoff i;//如果我将streamoff替换为pos_类型,编译器会抱怨
open(“basic_istream_tellg.txt”);
i=file.tellg();
文件>>c;

cout
pos\u type
是属于类的成员typedef,而不是命名空间作用域typedef。您需要类似于
ifstream::pos\u type
pos\u type
的内容。它是属于类的成员typedef,而不是命名空间作用域typedef。您需要类似于
ifstream::pos\u type
<写
pos\u type
,无需限定。请注意,它是
ifstream
的成员。因此,您必须写以下内容:

ifstream::pos_type i; //ok
现在应该可以了

另外,由于
使用了namespace std;
,因此您应该避免使用它,而应该更喜欢使用完全限定,如:

std::ifstream file;        //fully-qualified
std::ifstream::pos_type i; //fully-qualified
在C++11中,可以使用
auto

auto i = file.tellg();
并让编译器将
i
推断为
std::ifstream::pos_type


希望这能有所帮助。

您不能只编写
pos\u type
而不加限定。请注意,它是
ifstream
的成员。因此您必须编写以下内容:

ifstream::pos_type i; //ok
std::ifstream file;        
std::ifstream::pos_type i; 
现在应该可以了

另外,由于
使用了namespace std;
,因此您应该避免使用它,而应该更喜欢使用完全限定,如:

std::ifstream file;        //fully-qualified
std::ifstream::pos_type i; //fully-qualified
在C++11中,可以使用
auto

auto i = file.tellg();
并让编译器将
i
推断为
std::ifstream::pos_type

希望有帮助

std::ifstream file;        
std::ifstream::pos_type i; 

你可以使用它:它在DEV C++ +P/P中起作用。

 i = file.tellg();

你可以使用它:它在DEV C++ +P/P中起作用。

 i = file.tellg();

或者最好使用
auto
关键字,不要弄乱具体的typePerfect。我接受你的答案,因为这是我第一次得到答案。至于
使用名称空间std;
我只是从MSDN复制了代码。谢谢。本例中的
使用名称空间std;
至少在函数范围内,这是使用它最不臭的地方。@阿斯切普勒:我认为这没有多大区别,因为大多数代码通常在函数本身。在名称空间级别使用名称空间std;
编写
,在每个函数中使用名称空间std;
编写
几乎是一样的。或者最好使用
自动
关键字,不要弄乱具体的typePerfect。我接受您的答案,因为这是我第一次得到。至于
使用名称空间std;
我只是从MSDN复制了代码。谢谢。本例中
使用名称空间std;
至少在函数范围内,这是使用它最不臭的地方。@aschepler:我认为这没有多大区别,因为大多数代码通常都在函数中在名称空间级别使用名称空间std;
编写
,在每个函数中使用名称空间std;
编写
几乎是一样的事情。