我有以下类(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/