全部,
我在 foo.h 中有以下代码:
class __declspec(dllexport) Foo
{
protected:
struct Impl;
Impl *pimpl;
public:
std::wstring &GetMember() { return pimpl->m_string; };
};
struct Foo::Impl
{
std::wstring m_string;
};
不幸的是,这段代码产生了一个错误:
Use of undefined type 'Foo::Impl'
尝试转发声明 Database::Impl 会导致另一个编译器错误。
那么修复它的最佳方法是什么?
所有这些都在一个头文件中。
编辑:
我想我可以将函数放在实际的实现类中,但我真的想消除代码重复。但是,看起来我别无选择。
最佳答案
pimpl->m_string;
需要 pimpl
的类型(即 Foo::Impl
)为 complete type , 但稍后定义;仅前向声明是不够的,Foo::Impl
需要在之前定义。
而且我想您正在尝试实现 PImpl idiom ,通常用于减少编译时依赖性;所以你应该将 Foo::Impl
和 Foo::GetMember
的定义移动到一个实现文件中,比如
// Foo.h
class Foo
{
protected:
struct Impl;
Impl *pimpl;
public:
std::wstring &GetMember();
};
// Foo.cpp
#include "Foo.h"
struct Foo::Impl
{
std::wstring m_string;
};
// define Foo::GetMember after the definition of Foo::Impl
std::wstring &Foo::GetMember() { return pimpl->m_string; }
关于c++ - 接口(interface)类产生 "Use of undefined type",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44862454/