C++ virtual function return type(C++虚函数返回类型)
问题描述
继承的类是否可以实现具有不同返回类型的虚函数(不使用模板作为返回)?
Is it possible for an inherited class to implement a virtual function with a different return type (not using a template as return)?
推荐答案
在某些情况下,是的,只要返回类型为 ,派生类使用不同的返回类型覆盖虚函数是合法的与原始返回类型协变.例如,请考虑以下内容:
In some cases, yes, it is legal for a derived class to override a virtual function using a different return type as long as the return type is covariant with the original return type. For example, consider the following:
class Base {
public:
virtual ~Base() {}
virtual Base* clone() const = 0;
};
class Derived: public Base {
public:
virtual Derived* clone() const {
return new Derived(*this);
}
};
这里,Base
定义了一个名为 clone
的纯虚函数,它返回一个 Base *
.在派生实现中,使用 Derived *
的返回类型覆盖此虚函数.尽管返回类型与基类中的不同,但这是完全安全的,因为您可以随时编写
Here, Base
defines a pure virtual function called clone
that returns a Base *
. In the derived implementation, this virtual function is overridden using a return type of Derived *
. Although the return type is not the same as in the base, this is perfectly safe because any time you would write
Base* ptr = /* ... */
Base* clone = ptr->clone();
对 clone()
的调用将始终返回一个指向 Base
对象的指针,因为即使它返回一个 Derived*
,这个指针可以隐式转换为 Base*
并且操作是明确定义的.
The call to clone()
will always return a pointer to a Base
object, since even if it returns a Derived*
, this pointer is implicitly convertible to a Base*
and the operation is well-defined.
更一般地说,函数的返回类型永远不会被视为其签名的一部分.只要返回类型是协变的,您就可以使用任何返回类型覆盖成员函数.
More generally, a function's return type is never considered part of its signature. You can override a member function with any return type as long as the return type is covariant.
这篇关于C++虚函数返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++虚函数返回类型


基础教程推荐
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 这个宏可以转换成函数吗? 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09