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/