我正在尝试学习如何使用PIMPL习惯用法,因为它减少了编译依赖性,我建议你这样做。所以我的代码基本上就是这样。
foo.h中
class Foo
{
public:
Foo();
private:
class FooImpl;
std::unique_ptr<FooImpl> impl;
}
Foo.cpp中
Foo::Foo():
impl(new FooImpl)
{
}
class Foo::FooImpl
{
public:
FooImpl();
}
但现在我想在单独的.cpp文件中定义FooImpl::FooImpl()
,就像我对Foo::Foo()
所做的那样,但是我该如何去做呢?
编辑:我已经移动了以下代码,但现在初始化impl
会给我一个不完整的类型编译错误。
foo.h中
class Foo
{
public:
Foo();
private:
class FooImpl;
std::unique_ptr<FooImpl> impl;
}
Foo.cpp中
#include "Foo.h"
Foo::Foo():
impl(new FooImpl)
{
}
FooImpl.cpp
#include "Foo.h"
class Foo::FooImpl
{
public:
FooImpl();
}
答案 0 :(得分:3)
但是现在我想在一个单独的.cpp中定义FooImpl :: FooImpl()
疙瘩成语的想法是隐藏实现。去过那里。
但是,如果FooImpl类包含在Foo.cpp文件中(并且仅包含在该文件中),那么它已经被相当好地隐藏了。 (大多数c ++开发人员都会努力避免包含.cpp文件。
因此,您已经实现了疙瘩可以提供的减少依赖性的度量。
在为自己做更多的工作之前,尝试实现两个或三个类Foo的方法,然后发现如何在引入第三个文件之前将它们连接到Foo.cmpl文件中的FooImpl。
答案 1 :(得分:1)
我的解决方案是将你的FooImp定义在你的Foo类中。
让所有班级成员在那里。然后FooImp.cpp包含Foo.h并实现所有非内联函数。
我这样工作:
foo.h中
class Foo
{
public: // ctor & dtor
Foo();
~Foo();
private: // nested class
class FooImp
{
public:
FooImp();
~FooImp();
};
private: // member variable
std::unique_ptr<FooImpl> impl;
};
Foo.cpp中
#include "Foo.h"
Foo::Foo()
{
}
Foo::~Foo()
{
}
FooImp.cpp
#include "Foo.h"
Foo::FooImp::FooImp()
{
}
Foo::FooImp::~FooImp()
{
}
它汇编得很好。
答案 2 :(得分:0)
new new必须知道要分配的对象的大小,因此完整的FooImpl类声明必须可用于包含Foo构造函数的CPP文件,因为它使用“new FooImpl”。