代码之家  ›  专栏  ›  技术社区  ›  gsamaras a Data Head

为什么我不能在同一代码行中创建和打开一个ofstream?

  •  1
  • gsamaras a Data Head  · 技术社区  · 7 年前

    std::ofstream outfile; outfile.open("foo");
    

    但不是:

    std::ofstream outfile.open("foo");
    

    error: expected ';' at end of declaration
        std::ofstream outfile.open("foo");
                             ^
    

    你也可以在 Live Demo .

    为什么?

    我知道我可以 std::ofstream outfile("foo"); 但是我怀疑我缺少C++的机制,这就是我问的原因。

    7 回复  |  直到 7 年前
        1
  •  3
  •   463035818_is_not_an_ai    7 年前

    这类似于当您有一个返回对象的函数,并且希望在同一行中调用该函数的方法时:

    struct foo { void bar(){} };
    foo create_foo() { return foo(); }
    

    create_foo 或者使用其返回值来调用方法,但不能同时调用:

    create_foo().bar();          // OK
    auto f = create_foo();       // OK
    auto f = create_foo().bar(); // NOPE
    

    ofstream :你可以写

    std::ofstream().open("foo");
    

    但你就没有机会查到 .

        2
  •  8
  •   Swordfish    7 年前

    为什么?

    outfile 直到声明之后才存在。

    使用构造函数打开文件:

    std::ofstream outfile("foo");
    
        3
  •  2
  •   Lightness Races in Orbit    7 年前

    因为你不能。

    说真的。

    使用 void = 一个初始化器。

    但你已经知道了。

        4
  •  1
  •   Kevin Anderson    7 年前

    BufferedReader br = new BufferedReader(new FileReader(FILENAME));
    

    甚至Python:

    lines = open("filename").readlines();
    

    这里的诀窍是,使用正确的“工厂函数”,您也可以在C++中这样做,但这不是这个特定类的实现方式。上面的其他示例,包括以下任一示例:

    std::ofstream outfile{"foo"};
    auto outfile = std::ofstream("foo");
    

    open() 方法返回void: std::basic_ofstream::open() doc . 所以当你有了这个代码:

    std::ofstream outfile.open("foo");
    

    它不编译是因为 打开() 是一个成员函数(不是静态的),它返回 void std::ofstream ,这就是你宣称要做的。

    我希望这能帮你把事情弄清楚。

        5
  •  0
  •   user3520616 user3520616    7 年前

    std::ofstream outfile { "foo" };
    
        6
  •  0
  •   gsamaras a Data Head    7 年前

    因为语言。C++不允许这样的指令。

    使用构造函数

    std::ofstream outfile("foo");

    或初始化

    std::ofstream outfile { "foo" };

        7
  •  0
  •   Community Mohan Dere    6 年前

    std::ofstream outfile.open("foo");

    这是一个简单明了的语法错误。在这一点上, outfile ofstream .

    我们可能希望我们可以简单地这样解决它:

    auto outfile = std::ofstream().open("foo"); // call open on a constructed object.
    

    open 文件输出流

    // unexciting, but simple - uses a different constructor
    std::ofstream outfile{"foo"};
    

    这(IMHO)更具可读性,也更合法:

    auto outfile = std::ofstream("foo");