下面的代码段来自我的Keyboard.h
和Keyboard.cpp
。我的问题是,我将如何实现分层的父母和子女关系?因此,如果孩子没有实施任何虚拟成员,父母可以自由地这样做。例如,子实现KeyboardDepressA但不实现KeyboardDepressB,让父实现KeyboardDepressB的catch。父母和孩子当然也有不同的类型,而不是......
我不希望孩子知道父母的情况。支持Device::Keyboard
;因此,我想使用get实例调用父实例,如KeyboardDepressB
中所示。为了完成这项工作,我需要将父级分配给static
实例本身,但static
不支持关键字this
。那我该怎么办?
我将代码保持在最低限度。如果需要更多,请随时询问。 ^^
class Keyboard
{
private:
Keyboard ();
~Keyboard ();
public:
static Device::Keyboard& Instance();
static void SetParent(Device::Keyboard *cpParent);
virtual void KeyboardDepressA ();
virtual void KeyboardReleaseA ();
virtual void KeyboardDepressB ();
virtual void KeyboardReleaseB ();
… … ...
};
Device::Keyboard&
Keyboard::Instance()
{
static Device::Keyboard nrKeyboard;
return nrKeyboard;
} // member
void
Keyboard::SetParent(Device::Keyboard *cpParent)
{
Device::Keyboard& nrParent(Keyboard::Instance());
*this = cpParent;
} // member
void
Keyboard::KeyboardDepressA()
{
Device::Keyboard& nrParent(Keyboard::Instance());
nrParent.KeyboardDepressA();
} // member
void
Keyboard::KeyboardReleaseA()
{
Device::Keyboard& nrParent(Keyboard::Instance());
nrParent.KeyboardReleaseA();
} // member
void
Keyboard::KeyboardDepressB()
{
Device::Keyboard& nrParent(Keyboard::Instance());
nrParent.KeyboardDepressB();
} // member
void
Keyboard::KeyboardReleaseB()
{
Device::Keyboard& nrParent(Keyboard::Instance());
nrParent.KeyboardReleaseB();
} // member
答案 0 :(得分:1)
所以,一般来说,将继承与单例模式混合起来很复杂,所以要谨慎。
如果您有父子关系,在C ++中,父和/或子可以实现虚拟功能。
如果您希望父级实现它而不是子级:在父级中声明它是虚拟的,并为父级实现,但不为子级声明或实现它
class parent
{
public:
virtual void func();
}
void parent::func(){ ... }
class child : public parent
{
};
parent* p = new child;
p->func(); // calls parent's func
如果你想要一个被子进程覆盖的父实现:在父类和子类中将它声明为虚拟,并为两个类实现它(注意子进程可以调用父进程而不必了解实现是什么)
class parent
{
public:
virtual void func();
}
void parent::func(){ ... }
class child : public parent
{
virtual void func();
};
void child::func(){ ... parent::func();}
parent* p = new child;
p->func(); // calls child's func
如果您希望孩子实现它而父母不实现它:在父母中将其声明为纯虚拟成员,并为子女宣告并实施它
class parent
{
public:
virtual void func() = 0;
}
class child : public parent
{
virtual void func();
};
void child::func(){ ... }
parent* p = new child;
p->func(); // calls child's func