c++ - "Incomplete type not allowed "创建 std::ofstream 对象时

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

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

Incomplete type not allowed

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

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

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

最佳答案

正如@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 对象或引用其内容。当我们只有前向声明可用时,我们可能只能通过指针或引用来谈论它。

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


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

#include <iostream>

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

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

关于c++ - "Incomplete type not allowed "创建 std::ofstream 对象时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28882683/

相关文章:

c++ - 在这个输出中 7 是正确答案而不是 6

c++ - 非数字输入检查

c++ - STL vector 交换结构 (C++)

visual-studio - Visual Studio 2015 需要管理员权限

c# - 分析代码覆盖消失

visual-c++ - 在 .vcxproj 文件中,<ConfigurationType> 的可能值是什么?这些值是什么意思?

C++使用用户输入打开不同目录中的文件

c++ - 在 C++ 中引发异常和处理某些异常类型的正确方法是什么

c++ - QT 和 C++ : can't call function outside main() function

C++ std::istream readsome 不读取任何内容