问题描述
在 test.h
:
#ifndef TEST_H
#define TEST_H
#include <map>
struct Incomplete;
class Test {
std::map<int, Incomplete> member;
public:
Test();
int foo() { return 0; }
};
#endif
在 test.cpp
:
#include "test.h"
struct Incomplete {};
Test::Test() {}
在 main中。 cpp
#include "test.h"
int main() {
Test test;
return test.foo();
}
g ++ 4.7给我一个错误,指出 struct Incomplete
在我编写 g ++ main.cpp test.h -o main.o
时被向前声明。
g++ 4.7 gives me an error that struct Incomplete
is forward declared when I write g++ main.cpp test.h -o main.o
.
但是,如果更改 std :: map< int,Incomplete>成员
到 std :: map< int,Incomplete *>成员
, main.o
进行编译。为什么是这样?
However, if I change std::map<int, Incomplete> member
to std::map<int, Incomplete*> member
, main.o
compiles. Why is this?
推荐答案
因为未定义C ++标准库容器以使用不完整的成员类型。 – but it’s arguably an error (and might be changed in future versions of C++). The Boost.Containers library fixes this.
您的带指针代码可以工作,因为指向不完整类型的指针本身就是完整类型。但是,这显然会极大地改变您类型的语义(特别是谁来管理内存?),通常不建议使用它来代替。
Your code with pointers works because a pointer to an incomplete type is itself a complete type. However, this obviously changes the semantics of your type quite drastically (in particular, who manages the memory?) and it’s generally not a good idea to use this as a replacement.
值得指出的是,本文声称您在技术上不能实施 std :: map
使用不完整的类型。但是,这种说法是错误的。
It’s worth pointing out that the article claims that you technically cannot implement std::map
to work with incomplete types. However, this claim is wrong.
这篇关于无法在std :: map成员变量中分配具有正向声明值的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!