创建std::ofstream对象时,“不允许使用不完整类型”。

51

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

不允许不完整的类型

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

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

每当它遇到这个问题,Visual Studio就会抛出那个错误。为什么会发生这种情况?


38
你是否包含了 <fstream> 头文件? - Mgetz
1个回答

93
作为@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。但实际的std::ofstream定义在头文件中。

(注意:将来请务必提供最小完整可验证示例,而不仅仅是您代码中的一个函数。您应该提供一个完整的程序来演示问题。例如,这将更好地说明问题:

#include <iostream>

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

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接