简体   繁体   English

关于协变返回类型的C ++规则是什么?

[英]What the C++ rules in regard to covariant return types?

Like in the example below, what is allowed, how and why? 就像下面的例子一样,允许什么,如何以及为什么?

class Shape {
      public:
        //...
        virtual Shape *clone() const = 0; // Prototype
        //...
    };
    class Circle : public Shape {
      public:
        Circle *clone() const;
        //...
    };

C++ Standard 2003. 10.3.5 C ++ Standard 2003. 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: 如果函数D :: f覆盖函数B :: f,则函数的返回类型如果满足以下条件则是协变的:

— both are pointers to classes or references to classes - 两者都是类的指针或类的引用

— 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 - 返回类型B :: f中的类与D :: f的返回类型中的类相同,或者 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. - 指针或引用都具有相同的cv限定,并且返回类型D :: f中的类类型具有与B :: f的返回类型中的类类型相同的cv-qualification或更少的cv-qualification。

If the return type of D::f differs from the return type of B::f, the class type in the return type of D::f shall be complete at the point of declaration of D::f or shall be the class type D. When the overriding function is called as the final overrider of the overridden function, its result is converted to the type returned by the (statically chosen) overridden function (5.2.2). 如果D :: f的返回类型与B :: f的返回类型不同,则返回类型D :: f中的类类型应在D :: f的声明点完成,或者应该是类类型D.当重写函数被调用为重写函数的最终覆盖时,其结果将转换为(静态选择)重写函数(5.2.2)返回的类型。

Example: 例:

class B {};
class D : private B { friend class Derived; };
struct Base {
  virtual B*  vf4();
  virtual B*  vf5();
};
class A;
struct Derived : public Base {
  D* vf4();  // OK: returns pointer to derived class
  A* vf5();  // error: returns pointer to incomplete class
};

Pff, too long standard quoting. Pff,太长的标准报价。

You can use another type as covariant if (a) it is a pointer/reference (b) it can be casted to the prior return type by mere addition of a constant known at compilation time (c) it is compliant to all constant-volatile qualifiers. 如果(a)它是一个指针/引用,你可以使用另一种类型作为协变量(b)只需添加一个在编译时已知的常量就可以将它转换为先前的返回类型(c)它符合所有常量 - 易失性预选赛。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM