C++ 使用未定义类型

标签 c++

我有以下类(class):

class Logger {
    public:
    DEFAULT_CONSTRUCTOR(Logger);
    DEFAULT_DESTRUCTOR(Logger);
    NO_DEFAULT_COPY_AND_ASSIGN(Logger);

    bool Init(std::wstring logFileLocation, std::wstring assemblyVersion);
    void Shutdown();

    void const LogMessage(std::wstring message);

    private:
    struct LoggerImpl;
    std::unique_ptr<LoggerImpl> impl; // Error here
};

但是,在尝试编译时,出现以下错误:

// Errors:
// Error    1   error C2027: use of undefined type 'ophRuntime::Logger::LoggerImpl'
// Error    2   error C2338: can't delete an incomplete type    c:\program files (x86)\microsoft visual studio 12.0\vc\include\memory
// Warning  3   warning C4150: deletion of pointer to incomplete type 'ophRuntime::Logger::LoggerImpl'; no destructor called    c:\program files (x86)\microsoft visual studio 12.0\vc\include\memory

Logger::LoggerImpl 确实在相应的 .cpp 文件中有定义:

struct LoggerStream::LoggerStreamImpl {
    LoggerStreamImpl(std::wstring componentName) : componentName(componentName) { }

    const std::wstring componentName;

    NO_DEFAULT_COPY_AND_ASSIGN(LoggerStreamImpl);
};

最后,这些宏的定义:

#define NO_DEFAULT_COPY_AND_ASSIGN(TypeName)    \
    TypeName(const TypeName&) = delete;         \
    void operator=(const TypeName&) = delete;   \
    TypeName(TypeName&&) = default;             \

#define DEFAULT_CONSTRUCTOR(TypeName) TypeName();

#define DEFAULT_DESTRUCTOR(TypeName) ~TypeName();

最佳答案

在头文件中声明您的析构函数并在源文件中定义它。

在 .h 中

class Logger {
    public:
    Logger();  // default constructor
    ~Logger(); // default destructor

    private:
    struct LoggerImpl;                 // impl forward declaration
    std::unique_ptr<LoggerImpl> impl;  // impl pointer
};

在 .cpp 中

// Define the impl structure
struct Logger::LoggerImpl
{

};

// Define the default constructor
Logger::Logger() :impl(std::make_unique<LoggerImpl>())
{

}

// Define the default destructor
Logger::~Logger()
{

}

就是这样。

在你的例子中,你说 LoggerImpl 是这样在 .cpp 中定义的,但我没有看到 LoggerImpl 的定义,只是 的定义>LoggerStreamImpl.

关于C++ 使用未定义类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21357607/

相关文章:

c++ - 为什么这让我得到一个指向 const 对象字段的非常量指针?

c++ - 程序不会编译

c++ - 我对 N4140 中 [basic.link]/7 的理解是否正确?

c++ - 将构造函数参数转发给放置新运算符

c++ - boost::beast 同步 http 客户端超时

c++ - 关键字 "and"、 "or"和 "not"未定义

c++ - 使用 ? 返回可选值: operator

c++ - C++ 程序员应该避免 memset 吗?

c++ - 查找最大递归深度

c++ - WM_PAINT Bitblitting 多次?