调用基类的非虚函数中的基类虚函数
Calling a virtual function of the base class in a non virtual function of the base class
在基类的非虚函数中调用派生类中实现的基类的虚函数是否正确?就像
class A
{
virtual void func1() = 0;
void func2()
{
func1();
}
};
class B : public A
{
virtual void func1()
{
//do something here;
}
};
int main()
{
A* obj = new B;
obj->func2();
return 0;
}
是的,这将工作。你自己试过吗?
这不仅是一种众所周知的解决问题的有效方法,而且如果func2
是内联的,这可能意味着与直接调用内部函数相比,没有额外的开销。显然,有时整个目的是在func1
中做一些事情,然后在中间或最后调用func2
,但在额外工作最少的情况下,"额外功能层"可能完全消失。
是。当您需要操作符实现的虚函数行为时使用此技术:您根据虚(或抽象)函数定义操作符,并让专门化决定如何实现该函数。
的例子:
class base
{
// yada yada yada
base& operator=(const base& other) { return assign(other); }
protected:
virtual base& assign(const base& other) = 0; // specializations will decide
// what assignment means
};
编辑:该技术的另一个用途是允许类的专门化只控制更复杂操作的一部分:
class database
{
public:
void execute(const std::string& query)
{
begin_transaction(); // in practice, this should be RAII
connection_.execute(query);
end_transaction();
}
protected:
virtual void begin_transaction() = 0;
virtual void end_transaction() = 0;
private:
whatever &connection_;
};
在数据库专门化中,假设的mysql_database::begin_transaction
将具有与sqlite_database::begin_transaction
不同的实现。
可以。这允许您在基类中提供通用流,其详细信息在其子类中专门化。
相关文章:
- 基类中的函数名称解析
- 如何通过派生类函数更改基类中的向量
- 继承:构造函数,初始化C++11中基类的类C数组成员
- 使用基类指针创建对象时,缺少派生类析构函数
- 如果基类包含双指针成员,则派生类的构造函数
- C++ 继承:将子类传递给需要基类的函数并获取子类行为
- 继承和友元函数,从基类访问受保护的成员
- 使用子类覆盖基类中定义的函数
- 如何基于模板化类的基类专门化成员函数
- 基类中的默认析构函数禁用子类中的移动构造函数(如果有成员)
- 使用基类指针调用基类的值构造函数的语法是什么?
- C++重载函数,一个采用基类的参数,另一个采用派生类的参数
- 如何在基类指针向量的元素上应用重载的多态函数
- 如何在不使用指针的情况下将派生类的对象作为参数传递给基类中的函数?
- 被覆盖的函数不会反映在基类中,这是正常行为吗?
- 在初始化列表之外手动调用基类的构造函数
- 重写打印函数而不是覆盖基类
- C++17 使用驱动类常量作为基类构造函数的参数来初始化基类构造函数
- C++虚拟函数:基类函数是调用的,而不是派生的
- 虚拟函数-基类指针