#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.
virtual"构造函数 & 协变返回类
最新推荐文章于 2025-04-05 22:30:49 发布