gpt4 book ai didi

c++ - 静态选择函数和虚函数

转载 作者:太空狗 更新时间:2023-10-29 23:38:50 25 4
gpt4 key购买 nike

最近我看到了这个 C++ 标准段落(http://eel.is/c++draft/expr.post#expr.call-5):

If the postfix-expression designates a destructor, the type of the function call expression is void; otherwise, the type of the function call expression is the return type of the statically chosen function (i.e., ignoring the virtual keyword), even if the type of the function actually called is different. This return type shall be an object type, a reference type or cv void.

这部分我不太明白:

the type of the function call expression is the return type of the statically chosen function (i.e., ignoring the virtual keyword), even if the type of the function actually called is different.

  1. 这里静态选择的函数是什么?
  2. 如何静态选择虚函数?我一直认为它是在运行时选择的。
  3. even if the type of the function actually called is different.

调用表达式如何实际调用所选择的不同类型的函数?

最佳答案

虚函数可以有协变的返回类型,

所以

struct Base
{
virtual ~Base() = default;
virtual Base* Clone() const { return new Base(*this); }
};

struct Derived : Base
{
// covariant return type:
Derived* Clone() const override { return new Derived(*this); }
};

然后

Derived d;

Base& b = d;

auto* clonePtr = b.Clone(); // `auto` is `Base`, even if `Derived::Clone` is called.
// runtime type of `clonePtr` is `Derived`
std::unique_ptr<Base> clone(clonePtr); // Done in 2 steps for explanation

关于c++ - 静态选择函数和虚函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52423205/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com