gpt4 book ai didi

c++ - 模拟协变返回类型行为

转载 作者:搜寻专家 更新时间:2023-10-31 00:46:47 25 4
gpt4 key购买 nike

class Ancestor{};

class Descendant : public Ancestor{};

class Base
{
public:
Ancestor foo(void);
};

class Derived : public Base
{
public:
// Do not redefine foo as : Descendant foo(void);
};

我想以一种方式编写 Deriveds foo,当它被 Derived 对象调用时,它将返回 Descendant。我知道这可以通过使用协变返回类型轻松完成。但是,如果我无法使用此功能怎么办。我如何在上面的代码中模拟此功能?

最佳答案

I want to write Deriveds foo in a way that when it is called for a Derived object it will return Descendant.

// Do not redefine foo as : Descendant foo(void);

foo正在返回 Ancestor按值(value),实现(有限的)协方差的唯一方法是重新定义 foo .因此,要求是矛盾的

C++ 支持协变原始指针和原始引用结果。使用智能指针结果类型,例如 boost::shared_ptrstd::auto_ptr必须通过重新定义派生类中的公共(public)函数来实现协变。这与您的问题类似,因为协变函数按值返回——而不是原始指针或原始引用——但它也与您的问题不同,因为智能指针类型之间没有继承关系,而是向上转换。

这是一个例子:

#include <memory>
#include <typeinfo>
using namespace std;

struct Ancestor{ virtual ~Ancestor(){} };
struct Descendant : Ancestor {};

class Base
{
protected:
virtual Ancestor* virtualFoo() const
{
return new Ancestor();
}

public:
auto_ptr<Ancestor> foo() const
{
return auto_ptr<Ancestor>( virtualFoo() );
}
};

class Derived : public Base
{
protected:
virtual Descendant* virtualFoo() const
{
return new Descendant();
}

public:
auto_ptr<Descendant> foo() const
{
return auto_ptr<Descendant>( virtualFoo() );
}
};

#include <iostream>

int main()
{
Base baseObject;
Derived derivedObject;
Base& baseRef = derivedObject;

cout << typeid( *baseObject.foo() ).name() << endl;
cout << typeid( *derivedObject.foo() ).name() << endl;
cout << typeid( *baseRef.foo() ).name() << endl;
}

在前两个foo调用静态结果类型对应于动态类型,从使用代码的角度来看,这就是协方差的全部内容。

在最后foo调用 foo 的静态类型结果是 std::auto_ptr<Ancestor> , 而指针对象的类型是 Descendant .

请注意,虚函数的覆盖依赖于 C++ 对原始指针类型协变结果的内置支持。

干杯,

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

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