virtual"构造函数 & 协变返回类

本文通过一个具体的C++代码示例介绍了协变返回类型的概念及其应用。代码中定义了基类Shape及派生类Circle和Rect,并实现了clone和create方法,展示了如何正确使用协变返回类型来实现多态。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>
//Virtual constructor.
class Shape{
public:
    virtual ~Shape(void)
    { }

    virtual Shape* clone(void)const = 0;
    virtual Shape* create(void)const = 0;
};

class Circle : public Shape{
public:
    Circle* clone(void)const    //Covariant Return Types.See below.
    {
        std::cout<<"clone a circle.\n";
        return new Circle(*this);
    }
    Circle* create(void)const   //Covariant Return Types.
    {
        std::cout<<"create a circle.\n";
        return new Circle();
    }
};

class Rect : public Shape{
public:
    Rect* clone(void)const      //Covariant Return Types.
    {
        std::cout<<"clone a rectangle.\n";
        return new Rect(*this);
    }

    Rect* create(void)const     //Covariant Return Types.
    {
        std::cout<<"create a rectangle.\n";
        return new Rect();
    }
};
void user_code(const Shape& _Shape)
{
    Shape *s2 = _Shape.clone();
    Shape *s3 = _Shape.create();

    delete s2;
    delete s3;
}

int main(void)
{
    Circle c;
    user_code(c);

    Rect r;
    user_code(r);
}
//http://stackoverflow.com/questions/3593601/covariant-return-type
//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 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
// 
//— 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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值