我有一个类a,需要一个指向AA的指针才能工作,这是构造函数所要求的。我有一个从a继承的类B,为a提供了一个从AA继承的类BB。示例:
class A
{
public:
class AA
{
virtual void do_something() const;
};
protected:
const AA* aa;
public:
A(const A::AA* aa_) : aa(aa_) {}
void use() const { this->aa->do_something(); }
};
class B : public A
{
public:
class BB : public A::AA
{
virtual void do_something() const;
};
public:
B() : A(new BB()) {}
};
现在,我想把B实例的地址给BB实例。类似的东西:
class B : public A
{
public:
class BB : public A::AA
{
BB(B* b);
virtual void do_something() const;
};
public:
B() : A(new BB(this)) {}
// It doesn't work beacause the instance is not yet created
};
或者类似的东西:
class B : public A
{
public:
class BB : public A::AA
{
virtual void do_something() const;
void setPointer(B* b);
};
public:
B() : A(new BB()) { static_cast<BB*>(this->aa)->setPointer(this); }
// It doesn't work because this->aa is const
};
我该怎么做有没有解决这类问题的设计模式?
如果您只希望BB:BB存储指针,则
B() : A(new BB(this)) {}
应该还可以。
如果你想让它使用指针,那么你最好的选择是将指针存储在构造函数中,并在第二个函数中使用,如下所示:
B() : A(new BB(this)) { static_cast<const BB*>(this->aa)->UseStoredThis();
这假设您可以将UseStoredThis
标记为const。如果没有,那么您将需要:
B() : A(new BB(this))
{
const auto pcBB = static_cast<const BB*>(this->aa);
const auto pBB = const_cast<BB*>(pcBB);
pBB->UseStoredThis();
}
将AA::do_something
设为公共的或受保护的,并将BB
的构造函数设为公共,这将使代码可编译。
重构一点你也可以得到一个不错的版本:
class A {
public:
struct AA {
virtual void do_something() const;
};
A(A::AA const* aa_) : aa(aa_) {}
void use() const { this->aa->do_something(); }
protected:
AA const* aa;
};
struct B : public A {
struct BB : public A::AA {
BB(B* b) {}
virtual void do_something() const override;
};
B() : A(new BB(this)) {}
};
现场演示