我们无法创建抽象类的对象,对吧?那么如何调用在抽象基类和派生类中都有定义的虚函数呢?我想在抽象基类中执行代码,但是目前,我正在使用派生类的对象。
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调用基类函数?如果不可能,我应该怎么做才能调用基类函数?
答案 0 :(得分:4)
就像调用任何其他基类实现一样:使用显式限定来绕过动态调度机制。
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);
}
答案 1 :(得分:1)
您可以在调用函数时显式指定类范围:
class A { /* Abstract class */ };
class B : public A {}
B b;
b.A::foo();
答案 2 :(得分:1)
如果抽象基类有一些代码,那么只需调用BaseClassName :: AbstractFunction()
class Base
{
virtual void Function() {}
}
class Derived : Base
{
virtual void Function() { Base::Function(); }
}