gpt4 book ai didi

C++继承函数中的默认操作

转载 作者:搜寻专家 更新时间:2023-10-31 01:10:14 25 4
gpt4 key购买 nike

假设我有一个名为 Base 的抽象基类,它继承了另一个名为 Rectangle 的类(w/c 具有 x、y、w、h 的属性)

//Base.h

class Base abstract : public Rectangle
{
public:

Base();

void Show()
{

if (!visible) return;

//draw the stuff here.

}

virtual void PerformTask() = 0;

protected:

bool visible;
bool enable;
//other member variables

};

对于所有继承这个Base的类,它必须首先实现这个简短的操作:

void OtherClass1::PerformTask()
{

if (!enable) return; // <- this one I am referring to.

//else, proceed with the overriden operation

//...
}

PerformTask() 中,它是否可以进行默认操作,因为我不会在其所有实现中再次重新键入它,但同时被覆盖并且 short 操作先执行并保存?

最佳答案

是的,这是可以做到的;简单地使PerformTask 成为调用实际 覆盖函数的非虚函数:

// In Base:
void PerformTask() {
if (not enabled) return;

PerformTaskImpl();
}

virtual void PerformTaskImpl() = 0;

…然后在派生类中覆盖PerformTaskImpl

这实际上是一个很常见的模式。

关于C++继承函数中的默认操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16133392/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com