我有两个程序(ProgramA
和 ProgramB
)的工作接口(interface),我想尽可能地改进这两个程序的解耦。我要介绍的案例是从 ProgramA
调用 ProgramB
(Compute_Prop
) 的类,该类只能使用一些参数进行初始化我现在不提前。因此,我在标题中使用了一个指针。目前,我有这样的东西:
接口(interface).h
#include "programB.h" // loads Compute_Prop
class Compute {
public:
Compute();
Compute(targ1 arg1, targ2 arg2);
~Compute();
// some methods ...
private:
Compute_Prop* compute;
};
接口(interface).cpp
#include "programB.h"
#include "interface.h"
#include "programA.h"
Compute::Compute() = default;
Compute::~Compute() {
delete compute;
}
Compute::Compute(arg1, arg2) {
// do something ... to get data
compute = new Compute_Prop( &data, arg2 );
}
然后,我试着用下面的方式模仿 PIMPL 的成语
接口(interface).h
#include "programB.h" // loads Compute_Prop
class Compute {
public:
Compute();
Compute(targ1 arg1, targ2 arg2);
~Compute();
// some methods ...
private:
class PIMPL;
PIMPL* compute;
};
接口(interface).cpp
#include "programB.h"
#include "interface.h"
#include "programA.h"
Compute::PIMPL = Compute_Prop;
Compute::Compute() = default;
Compute::~Compute() {
delete compute;
}
Compute::Compute(arg1, arg2) {
// do something ... to get data
compute = new Compute_Prop( &data, arg2 );
}
但是编译器说:
error: expected unqualified-id
Compute::PIMPL = Compute_Prop;
^
我猜这与 Compute_Prop 没有
一个空的构造函数。我想不出有用的东西。我应该怎么办?也许是指向指针的指针?作为限制,我不能修改 programB
。
注意:由于上面可能已经很清楚,我对低级 C++/C 的理解很少。
编辑:我介绍了@n.m 建议的更正。和@Matthieu Brucher
最佳答案
您的实现应该使用一个接口(interface)(或者实际上是一个只有抽象方法的类)作为基类。 您不能在 C++ 中分配类型。您只能像这样创建 typedef 和别名:
using PIMPLType = Compute_Prop;
但是这对你的情况不起作用。 这是它应该如何实现的(也有多种实现的可能性):
class IImplementation
{
public:
virtual void saySomething() = 0;
};
class ImplementationA : public IImplementation
{
public:
virtual void saySomething() override {
std::cout << "A";
}
};
class ImplementationB : public IImplementation
{
public:
virtual void saySomething() override {
std::cout << "B";
}
};
class Foo {
IImplementation *pimpl;
public:
Foo()
: pimpl(new ImplementationA)
{}
~Foo() { delete pimpl; }
void saySomething() {
pimpl->saySomething();
}
};
关于c++ - PIMPL 习惯用法,用于指向 C++ 中的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53288192/