gpt4 book ai didi

c++ - 我可以在覆盖虚函数的返回类型中丢失 "constness"吗?

转载 作者:IT老高 更新时间:2023-10-28 21:57:29 27 4
gpt4 key购买 nike

以下代码编译运行,gcc 或 clang 均未发出警告:

#include <iostream>

struct Base {
virtual ~Base() = default;
virtual std::string const& get() = 0;
};

struct Derived: Base {
virtual std::string& get() override { return m; }
std::string m;
};

int main()
{
Derived d;
d.get() = "Hello, World";

Base& b = d;
std::cout << b.get() << "\n";
}

std::string& 是否与 std::string const& 协变呢?

最佳答案

是的

这是在 class.virtual 中指定的,在我们看到的最新草案 (n4606) 中:

§10.3 7/ The return type of an overriding function shall be either identical to the return type of the overridden function or covariant with the classes of the functions. If a function D::f overrides a function B::f, the return types of the functions are covariant if they satisfy the following criteria:

  • both are pointers to classes, both are lvalue references to classes, or both are rvalue references to classes111
  • the class in the return type of B::f is the same class as the class in the return type of D::f, or is an unambiguous and accessible direct or indirect base class of the class in the return type of D::f
  • both pointers or references have the same cv-qualification and the class type in the return type of D::f has the same cv-qualification as or less cv-qualification than the class type in the return type of B::f.

具体来说,最后一点正好解决了这里的情况:重写类型丢失 const 和/或 volatile 限定符是可以接受的(但是,它不能,获得它们)。


注意:如 @george 所述上面的第 8 段/用于防止它使用不完整的类类型,但这是 since fixed .

关于c++ - 我可以在覆盖虚函数的返回类型中丢失 "constness"吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39869216/

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