简体   繁体   English

std::fstream 是 class 但使用命名空间语法引用 std::fstream::trunc ?

[英]std::fstream is a class but references std::fstream::trunc using namespace syntax?

I was getting some help on creating files with fstream, but came across this method where you pass std::fstream::trunc to the constructor.我在使用 fstream 创建文件时获得了一些帮助,但遇到了将 std::fstream::trunc 传递给构造函数的方法。

I was curious as to how fstream is a class, but referencing the trunc member is like fstream is a namespace (fstream::trunc, like NAMESPACE::MEMBER).我很好奇 fstream 如何是 class,但引用 trunc 成员就像 fstream 是一个命名空间(fstream::trunc,如 NAMESPACE::MEMBER)。

How is this done?这是怎么做到的?

trunc is a static member of the class std::ios_base . trunc是 class std::ios_base的 static 成员。 To access static members you need to use the class name where they are declared or an object of the class.要访问 static 成员,您需要使用声明它们的 class 名称或 ZA2F2ED4F8DCEBC2CBBDZC21A2 的 object 名称。

Here is a demonstration program这是一个演示程序

#include <iostream>

namespace N
{
    class A
    {
    public:
        inline static int x = 10;
    };

    class B : public A
    {
    };
}

int main()
{
    std::cout << N::B::x << '\n';
}

The program output is程序 output 是

10

Or you could declare the static data member like for example或者您可以声明 static 数据成员,例如

const static int x = 10;

or或者

constexpr static int x = 10;

Or you could declare it within the class like或者您可以在 class 中声明它,例如

static int x;

and then define it outside the class like然后在 class 之外定义它

int A::x = 10;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM