gpt4 book ai didi

c++ - 协变返回类型

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:00:09 25 4
gpt4 key购买 nike

$10.3/5

"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 or references to classes98)

— 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.

struct A{};
struct B : A{};

struct X{
virtual const A * const f(){return 0;}
};

struct Y : X{
virtual const B * volatile f(){return 0;}
};

int main(){
Y b;
X &r = b;
r.f();
}

我写了上面的实验代码,发现 Comeau 的错误/警告不一致。第 9 行中的警告似乎表明返回类型中的 cv 限定符没有意义。正是这个原因导致代码格式错误。

"ComeauTest.c", line 5: warning: type qualifier on return type is meaningless
virtual const A * const f(){return 0;}
^

"ComeauTest.c", line 9: warning: type qualifier on return type is meaningless
virtual const B * volatile f(){return 0;}
^

"ComeauTest.c", line 9: error: return type is not identical to nor covariant with
return type "const A *const" of overridden virtual function function
"X::f"
virtual const B * volatile f(){return 0;}
^

那么问题来了,Comeau 在第 9 行发出“警告”信息是否正确?我知道这是一个实现定义的行为,而 Comeau 只是想表现得很好。但在这种情况下,充其量只是令人困惑。

最佳答案

第 5 行和第 9 行的警告“返回类型上的类型限定符无意义”是因为非类类型右值永远不会被 cv 限定。

由于按值返回的函数的结果是右值,而指针是非类类型,因此返回的指针不是 cv 限定的,即使返回类型表明它是。

此警告与协方差无关。以下函数会导致相同的警告:

int* volatile f() { return 0; }

至于 10.3/5 的引用文本:

both pointers or references have the same cv-qualification

这是指返回类型的顶级限定(即const int* volatile中的volatile)。虽然顶级限定没有意义,但它确实会影响函数的类型,因此鉴于上面的 f 声明,此片段是不正确的:

int* (*q)() = f; // error:  can't convert int* volatile (*)() to int* (*)()

同样,如果派生类成员函数中返回类型的顶级 cv 限定与基类中返回类型的顶级 cv 限定不匹配,则派生类成员函数不会覆盖基类成员函数。

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 int* volatile中的const)。该规则意味着派生类成员函数中返回类型的限定必须等于或小于它覆盖的基类成员函数的返回类型。

关于c++ - 协变返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3593601/

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