创建std :: ofstream对象时"不允许不完整类型"

aru*_* vs 19 c++ fstream ofstream visual-studio-2013

Visual Studio引发此奇怪错误:

不允许不完整的类型

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

void OutPutLog()
{
     std::ofstream outFile("Log.txt");
}
Run Code Online (Sandbox Code Playgroud)

每当遇到此Visual Studio时抛出该错误.为什么会发生这种情况?

Hos*_*ork 41

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

你没有得到not declared错误的原因,而是这个incomplete type not allowed错误与当一个类型已经"向前声明"但尚未完全定义时发生的情况有关.

看看这个例子:

#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);
}
Run Code Online (Sandbox Code Playgroud)

请注意,在实际定义之后,我们无法实际实例化Foo对象或引用其内容.当我们只提供前向声明时,我们可能只会通过指针或引用来讨论它.

可能发生的事情是你包含了一些std::ofstream以类似的方式向前声明的iostream标题.但实际的定义std::ofstream是在<fstream>标题中.


(注意:将来一定要提供一个最小的,完整的,可验证的示例,而不是代码中的一个函数.你应该提供一个演示问题的完整程序.这样会更好,例如:

#include <iostream>

int main() {
    std::ofstream outFile("Log.txt");
}
Run Code Online (Sandbox Code Playgroud)

...另外,"输出"通常被视为一个完整的单词,而不是两个作为"OutPut")