我们不能创建抽象类的对象,对吧?那么如何调用在抽象基类和派生类中都有定义的虚函数呢?我想在抽象基类中执行代码,但目前,我正在使用派生类的对象。
class T
{
public:
virtual int f1()=0;
virtual int f2() { a = 5; return a }
}
class DT : public T
{
public:
int f1() { return 10; }
int f2() { return 4; }
}
int main()
{
T *t;
t = new DT();
............
}
有什么方法可以使用对象 t 调用基类函数吗?如果不行,调用基类函数需要做什么?
最佳答案
就像调用任何其他基类实现一样:使用显式限定来绕过动态调度机制。
struct AbstractBase
{
virtual void abstract() = 0;
virtual bool concrete() { return false; }
};
struct Derived : AbstractBase
{
void abstract() override {}
bool concrete() override { return true; }
};
int main()
{
// Use through object:
Derived d;
bool b = d.AbstractBase::concrete();
assert(!b);
// Use through pointer:
AbstractBase *a = new Derived();
b = a->AbstractBase::concrete();
assert(!b);
}
关于c++ - 在 C++ 中,如何调用在抽象基类和派生类中都有定义的基类的虚函数定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38010286/