c++ - 接口(interface)类产生 "Use of undefined type"

标签 c++ c++11

全部,

我在 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::ImplFoo::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/

相关文章:

python - 带有额外模块的 OpenCV 3.0.0 - imgproc 依赖

c++ - 实现自定义 Gtkmm 小部件 : what should I return in the virtual on_* functions?

c# - 具有大量客户端的套接字编程中的客户端到客户端通信

c++ - 不存储成员函数 c++ 的返回值是否被认为是不好的做法

c++ - 迭代基本类型时使用 const 引用有什么缺点吗?

c++ - 如何检查类型是否可显式/隐式构造?

c++ - 如何在 C++ 中从一个字符串流对象复制到另一个?

c++ - 如何返回 lambda 对象?

c++ - 为什么自由函数指针总是指针类型,而成员函数指针实际上不是指针?

c++ - type_traits - 连续内存