我刚才注意到我可以在抽象类本身中实现纯虚函数。海湾合作委员会不抱怨。有没有使用这种实施?任何人都可以使用它吗?
class AbstractClass
{
virtual void PureVirtualFunction() = 0;
};
void AbstractClass::PureVirtualFunction() //Is there any use of this implementation?
{
cout << "I am inside pure virtual function of AbstractClass" << endl;
}
class DerivedClass : public AbstractClass
{
public:
void PureVirtualFunction();
};
void DerivedClass::PureVirtualFunction()
{
cout << "I am inside pure virtual function of DerivedClass" << endl;
}
答案 0 :(得分:4)
您可以使用它来提供派生类可以访问的默认实现。
一个可能的用途是&#34;亲爱的派生类作者,这个虚拟函数非常重要,我想确保你知道你正在做什么。我将提供默认实现,但您必须明确使用它。&#34;这将是这样做的:
class AbstractClass
{
public:
virtual void PureVirtualFunction() = 0;
};
void AbstractClass::PureVirtualFunction() //Is there any use of this implementation?
{
cout << "I am inside pure virtual function of AbstractClass" << endl;
}
class DerivedClass : public AbstractClass
{
public:
void PureVirtualFunction();
};
void DerivedClass::PureVirtualFunction()
{
AbstractClass::PureVirtualFunction();
}
答案 1 :(得分:1)
例如,您可以从DerivedClass
实施中调用它(如果AbstractClass::PureVirtualFunction
不是私有的):
void DerivedClass::PureVirtualFunction()
{
AbstractClass::PureVirtualFunction();
cout << "I am inside pure virtual function of DerivedClass" << endl;
}
即使它是私密的,您也可以从AbstractClass
本身拨打电话:
class AbstractClass
{
virtual void PureVirtualFunction() = 0;
public:
void CallPureVirtualFunction() {
AbstractClass::PureVirtualFunction();
}
};
DerivedClass().CallPureVirtualFunction();
I am inside pure virtual function of AbstractClass