我如何调用基类的虚拟函数定义,这些定义在Ampract Base类和C 中的派生类中都有定义
How can I call virtual function definition of base class that have definitions in both abstract base class and derived class in C++?
我们无法创建一个抽象类的对象,对吗?那么,如何调用在抽象基类和派生类中都具有定义的虚拟函数呢?我想在抽象基类中执行代码,但目前,我正在使用派生类的对象。
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);
}
您可以在调用函数时明确指定类范围:
class A { /* Abstract class */ };
class B : public A {}
B b;
b.A::foo();
如果抽象基类有一些代码,则只需致电baseclassname :: AbstractFunction()
class Base
{
virtual void Function() {}
}
class Derived : Base
{
virtual void Function() { Base::Function(); }
}
相关文章:
- 在提升multi_index容器中,是否定义了"default index"?
- #定义c-预处理器常量..我做错了什么
- 用C++中的一个变量定义一个常量
- 部分定义/别名模板模板参数
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- #为""定义宏;静态";针对不同的上下文
- 如何确保C++函数在定义之前声明(如override关键字)
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 当类在C++中定义时,有什么方法可以"register"类吗?
- 在命名空间中定义函数还是限定函数
- 此代码是否违反一个定义规则
- 编译C++时未定义的引用
- 不同翻译单元中不可重载的非内联函数定义
- 为什么在定义函数之前先声明它
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- 在类定义之后定义一个私有方法
- 我如何调用基类的虚拟函数定义,这些定义在Ampract Base类和C 中的派生类中都有定义
- 对Base::run();的未定义引用;
- 未定义对Base::object链接器错误@c++w/freeglut的引用
- C++ CRTP 并从 base 访问派生的嵌套类型定义