【问题标题】:"Incomplete type not allowed " when creating std::ofstream objects创建 std::ofstream 对象时“不允许不完整类型”
【发布时间】:2023-09-03 17:05:02
【问题描述】:

Visual Studio 抛出这个奇怪的错误:

不允许不完整的类型

当我尝试创建一个 std::ofstream 对象时。这是我在函数中编写的代码。

void OutPutLog()
{
     std::ofstream outFile("Log.txt");
}

每当遇到此 Visual Studio 时都会引发该错误。为什么会这样?

【问题讨论】:

  • 您是否加入了<fstream>
  • 包括 fstream 解决了我的问题。谢谢

标签: c++ visual-studio-2013 fstream ofstream


【解决方案1】:

正如@Mgetz 所说,您可能忘记了#include <fstream>

您没有收到 not declared 错误而出现此 incomplete type not allowed 错误的原因与当存在 "forward declared" 但尚未完全定义的类型时发生的情况有关。

看这个例子:

#include <iostream>

struct Foo; // "forward declaration" for a struct type

void OutputFoo(Foo & foo); // another "forward declaration", for a function

void OutputFooPointer(Foo * fooPointer) {
    // fooPointer->bar is unknown at this point...
    // we can still pass it by reference (not by value)
    OutputFoo(*fooPointer);
}

struct Foo { // actual definition of Foo
    int bar;
    Foo () : bar (10) {} 
};

void OutputFoo(Foo & foo) {
    // we can mention foo.bar here because it's after the actual definition
    std::cout << foo.bar;
}

int main() {
    Foo foo; // we can also instantiate after the definition (of course)
    OutputFooPointer(&foo);
}

请注意,在真正的定义之后之前,我们无法实际实例化 Foo 对象或引用其内容。当我们只有前向声明可用时,我们可能只能通过指针或引用来谈论它。

可能发生的情况是您包含了一些以类似方式前向声明 std::ofstream 的 iostream 标头。但std::ofstream 的实际定义在&lt;fstream&gt; 标头中。


(注意:以后一定要提供一个Minimal, Complete, Verifiable Example,而不是只提供一个函数。你应该提供一个完整的程序来演示这个问题。这样会更好,例如:

#include <iostream>

int main() {
    std::ofstream outFile("Log.txt");
}

...另外,“Output”通常被视为一个完整的单词,而不是两个“OutPut”)

【讨论】:

    最近更新 更多