C++ 带C+的PImpl+;:为什么代码不起作用?
我通过将C++ 带C+的PImpl+;:为什么代码不起作用?,c++,pimpl-idiom,C++,Pimpl Idiom,我通过将#include“stdafx.h”放在#include“PImplTest.h”之前而不是之后解决了这个问题(很抱歉,原始问题中遗漏了此语句) 但我仍然不明白为什么它不能在它之后留下来 // stdafx.h #include <tinyxml2.h> #include <queue> #include <map> #include <vector> #include <list> #include <set> #
#include“stdafx.h”
放在#include“PImplTest.h”
之前而不是之后解决了这个问题(很抱歉,原始问题中遗漏了此语句)
但我仍然不明白为什么它不能在它之后留下来
// stdafx.h
#include <tinyxml2.h>
#include <queue>
#include <map>
#include <vector>
#include <list>
#include <set>
#include <stack>
#include <string>
#include <memory>
#include <assert.h>
VS报告上述代码注释中的2个错误。但是,如果在如下文件中实现:
// PImplTest.cpp
#include "PImplTest.h"
#include "stdafx.h" // this statement was missed in my first post
class PImpl::Impl // error C2079 'Impl' uses undefined class 'PImpl'
{ // error C2653 'PImpl':is not a class or namespace name
};
// main.cpp
#include "PImplTest.h"
class PImpl::Impl
{
};
int main()
{
return 0;
}
那就没什么问题了
有什么问题吗?如何修复它?这些是唯一的
#include
指令,特别是您是否有其他包含或包含在PImplTest.h
中的头文件?不,这些都是代码头文件:您需要添加~Pimpl()在标题中的code>和Pimpl::~Pimpl()=default在您的cpp文件中进行编码>,以便在Impl
完成时实例化std::unique_ptr
的析构函数。您引用的第一条错误消息是由编译器输出的吗?非常抱歉,在第一种情况下,在PImplTest.cpp文件中的“#include”PImplTest.h”之后缺少一行代码,即“#include”stdafx.h”。当我把它放在PImplTest.h的include语句之前时,一切都是对的。但是我仍然很困惑,为什么pch的include应该在PImplTest.h的include之前保留?这些是唯一的#include
指令吗,尤其是您是否有其他包含或包含在PImplTest.h
中的头?不,这些都是代码头:您需要添加~Pimpl()在标题中的code>和Pimpl::~Pimpl()=default在您的cpp文件中进行编码>,以便在Impl
完成时实例化std::unique_ptr
的析构函数。您引用的第一条错误消息是由编译器输出的吗?非常抱歉,在第一种情况下,在PImplTest.cpp文件中的“#include”PImplTest.h”之后缺少一行代码,即“#include”stdafx.h”。当我把它放在PImplTest.h的include语句之前时,一切都是对的。但是我仍然很困惑,为什么pch的包含应该在PImplTest.h的包含之前?
// main.cpp
#include "stdafx.h" // this statement was missed in my first post
#include "PImplTest.h"
int main()
{
return 0;
}
// main.cpp
#include "PImplTest.h"
class PImpl::Impl
{
};
int main()
{
return 0;
}