协变虚函数返回类型问题 [英] Covariant virtual functions return type problem

查看:331
本文介绍了协变虚函数返回类型问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

#include <iostream>
using namespace std;

class Child1
{
    int i;
};

class Child2 : public Child1
{
    int j;
};

class Base1
{

public:

    virtual Child1& getChildren()
    {
        cout << "Children1" << endl;
        return children;
    }

private:

    Child1 children;
};

class Base2 : public Base1
{

public:

    virtual Child2& getChildren()
    {
        cout << "Children2" << endl;
        return children;
    }

private:

    Child2 children;
};

此代码编译正常,但当我更改 getChildren()的返回类型时, Base1 Base2 (如)中的引用类型到对象类型 c $ c> virtual Child2 getChildren(),我在Visual Studio 2010上得到以下错误:

This code compiles fine but when I change the return type of getChildren() from reference type to object type in either or both Base1 and Base2 (e.g. virtual Child2 getChildren(), I get the following error on Visual Studio 2010:

error C2555: 'Base2::getChildren': overriding virtual function return type differs and is not covariant from 'Base1::getChildren'

我想知道为什么我得到这个错误时使用参考和得到它不是这是VS2010中的一个错误因为C ++标准(根据 Microsoft 网站上的此页面)说明:覆盖函数的返回类型应为与重写函数的返回类型或与函数类的协变量相同。并且在B :: f的返回类型中的类是与返回类型D中的类相同的类:: f或,是D :: f的返回类型中类的一个明确的直接或间接基类,可在D中访问。

I want to know why am I not getting this error when using reference and getting it otherwise. Is this is a bug in VS2010? Because the C++ standard (according to this page on Microsoft's website) says something like: 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. And 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 direct or indirect base class of the class in the return type of D::f and is accessible in D.

PS我目前无法访问该标准,因此无法验证上述报价。

P.S. I do not have access to the standard at the moment so can not verify the above quote.

推荐答案

您错过了其他部分引用:如果函数D :: f覆盖函数B :: f,则函数的返回类型是协变的,如果它们满足以下标准:(1)都是指针类或引用添加到类

You missed the other part they quoted: "If a function D::f overrides a function B::f, the return types of the functions are covariant if they satisfy the following criteria: (1) both are pointers to classes or references to classes"

这篇关于协变虚函数返回类型问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆