什么时候应该重新定义非虚方法
When should a non-virtual method be redefined?
virtual
方法是多态性的c++实现的一部分。除了避免与RTTI**和方法查找相关的开销外,是否有令人信服的理由省略virtual
?
假设virtual
可以随时添加到基类中,那么重新定义非virtual
方法的目的是什么?
**在现代cpu上是否可测量与此问题无关。
好吧,没有什么理由重新定义一个非虚函数。实际上,我不建议这样做,因为基于所使用的指针/引用的静态类型,对完全相同对象的相同函数调用可能表现不同。
重写虚成员函数允许您专门化派生类型的行为。重载非虚成员函数将提供另一种行为,在这种行为中,对于一般读者来说,可能不太明显将执行哪个函数/行为。
一个可能的用途是实现一个CRTP框架,其中定义了函数的默认版本:
#include <iostream>
//This could be any higher-order function.
template<typename T>
class CallFiveTimes {
protected:
void docalls() const {
for(int i(0); i != 5; ++i) static_cast<T const*>(this)->callme();
}
//Default implementation. If a lot
//of different functionality were required of `T`
//then defaults could make `T` easier to write.
void callme() const {
std::cout << "Default implementation.n";
}
};
class Client : CallFiveTimes<Client> {
public:
void useFramework() {
docalls();
}
private:
friend struct CallFiveTimes<Client>;
//This redefinition will be used.
void callme() const {
std::cout << "Client implementation.n";
}
};
class LazyClient : CallFiveTimes<LazyClient> {
public:
void useFramework() {
docalls();
}
friend struct CallFiveTimes<LazyClient>;
};
int main() {
Client c;
c.useFramework(); //prints "Client Implementation" five times
LazyClient lc;
lc.useFramework(); //prints "Default Implementation" five times
}
我从未在实践中见过这样做,但在某些情况下可能值得考虑。
相关文章:
- 在父类中为多个子类定义方法
- 在.cpp文件中定义方法而不是在 C++ 的 .h 文件中定义方法时,如何提高代码的性能?
- 对已定义方法的未定义引用
- 需要派生的类来定义方法
- 在某些名称空间中定义方法时,在全局名称空间中声明
- 在类 C++ 中重定义方法
- 这两种定义方法的样式之间是否存在差异
- 对已定义方法的未定义引用、标头中的声明和源匹配
- 如果未在类 c++ 中定义方法,如何在类对象上使用方法
- 在为嵌入式类定义方法时,有没有办法避免重复包含类
- 有关C++中一个或多个乘法定义方法的错误
- 在 cpp 文件中定义方法时未解析外部,但在标头中定义时未解析
- 是否允许所有未使用的未定义方法
- 如何在声明之外为专门用于无参数的可变模板类定义C++方法
- 什么是编程语言为派生类重新定义方法的能力
- 在C++中,在类定义内部或外部定义方法体是否更为传统
- 向std::vector或typdef添加自定义方法
- 如果在头文件中定义方法,内联关键字有什么用?
- C++ 我知道数组长度,但想知道是否是一种更简洁的数组元素定义方法
- 在类作用域内定义方法时,除非在原始 cpp 文件中的其他位置调用方法,否则项目不会编译