【问题标题】:Forcing late method resolution in case of class inheritance in c++在 C++ 中的类继承的情况下强制延迟方法解析
【发布时间】:2014-02-24 14:51:40
【问题描述】:

考虑以下类结构:-

    class foo {
    public:
      int fun () {
        cout << "in foo" << endl;
      }
    };

    class bar_class1:public foo {
    public:
      int fun () {
        cout << "in bar_class1" << endl;
      }
    };

    class bar_class2:public foo {
    public:
      float fun () {
        cout << "in bar_class2" << endl;
      }
    };

    main () {
      foo * foo_pointer = new bar_class1();
      foo_pointer->fun();
    }

上述程序的输出是in foo。有没有办法,使用foo * 类型的指针,它实际上指向bar_class1 或bar_class2 类型的对象,我们可以调用派生类的fun 函数而不是基类?我无法将基类foo 中的fun 函数设为虚函数,因为派生类bar_class2 中的函数foo 存在返回类型冲突。

【问题讨论】:

  • 您是否可以将其设为虚拟,然后让 bar_class2 实现 int fun() 并将其委托给私有 float fun()?
  • 您的示例有点混乱,因为成员函数具有返回类型,但它们不返回任何内容,并且调用者不使用返回值。
  • @chris 你的建议不清楚。能详细点吗?
  • 如果这种多态性是可能的,那么当代码在实际类型为bar_class2 的对象上调用foo::fun(期望一个int)并因此得到一个浮点数时,这不会很糟糕吗?你想简单地抛弃类型安全吗?
  • @SagarJha 不,这不安全。因为调用者不知道返回类型。假设你这样做:int result = foo_pointer-&gt;fun(); 如果fun 返回一个浮点数怎么办?你怎么知道你得到的是浮点数还是整数? C++ 不允许这样做。编译器必须在编译期间知道类型。

标签: c++ oop inheritance overload-resolution


【解决方案1】:

这是我的 cmets 作为答案。

你不能这样做。

如果这种多态性是可能的,那么当代码调用foo::fun(期望一个int)对一个实际类型为bar_class2 并因此得到一个浮点数的对象时,这会不会很糟糕?你想简单地抛弃类型安全吗?

如果你想要不同的返回类型,听起来你想要一个模板。但是你不能完全按照你想要使用 foo() 的方式使用模板。静态多态性(模板)和运行时多态性(后期绑定)不能很好地混合。您需要重新设计您的 oop 结构。

如果您绝对讨厌类型安全,您可以在某种程度上使用 void 指针来做到这一点。 但是为了爱飞翔的意大利面怪物,千万不要在c++中这样做。请在阅读以下代码之前闭上眼睛,以免暴露。

#include <iostream>

class foo {
public:
    virtual void* fun() = 0;
    virtual ~foo(){};
};

class bar_class1: public foo {
public:
    void* fun() {
        return &value;
    }
private:
    int value = 1;
};

class bar_class2: public foo {
public:
    void* fun() {
        return &value;
    }
private:
    float value = 1.1;
};

int main() {
    foo* foo_pointer1 = new bar_class1();
    foo* foo_pointer2 = new bar_class2();

    // in c++ compiler must know the type of all objects during compilation
    std::cout << *reinterpret_cast<int*>(foo_pointer1->fun()) << '\n';
    std::cout << *reinterpret_cast<float*>(foo_pointer2->fun()) << '\n';
    delete foo_pointer1;
    delete foo_pointer2;
}

【讨论】:

  • 这些苛刻的建议真的对任何人都有帮助吗?
  • @Wolf 它告诉提问者他所要求的不能以类型安全的方式完成。他的要求在类型安全的语言中没有任何意义。我相信我的回答可以帮助任何考虑这种设计的人理解他们需要重新设计(希望代码可以帮助他们理解为什么需要)。如何进行重新设计很大程度上取决于他们打算如何处理他们的课程。从他的问题中无法判断 OP 打算做什么。
【解决方案2】:

也许类似于现有的答案,我真的希望你意识到改变你的设计比这个烂摊子更好,但我相信这是你会得到的最好的。我强迫你在调用点指定返回类型(例如,someFoo-&gt;fun&lt;int&gt;()),因为无论如何你都必须知道它,并根据它进行调度。任何有趣的事情,你都会得到一个例外。另外请记住,我认为它的性能不太理想。

#include <cassert>
#include <stdexcept> 
#include <type_traits> 

struct foo {       
    virtual ~foo() = default;

    template<typename T, typename = typename std::enable_if<std::is_same<T, int>::value>::type, typename = void>
    T fun();

    template<typename T, typename = typename std::enable_if<std::is_same<T, float>::value>::type>
    T fun();
};

struct bar_class1 : foo {
    int fun() {
        return 2;
    }
};

struct bar_class2 : foo {
    float fun() {
        return 3.5f;
    }
};

template<typename T, typename, typename Dummy>
T foo::fun() {
    if (auto *p = dynamic_cast<bar_class1 *>(this)) {
        return p->fun();
    } else if (dynamic_cast<bar_class2 *>(this)) {
        throw std::invalid_argument("Mismatching dynamic type.");
    } else {
        return 1;
    }
}

template<typename T, typename>
T foo::fun() {
    auto *p = dynamic_cast<bar_class2 *>(this);

    if (dynamic_cast<bar_class1 *>(this) || !p) {
        throw std::invalid_argument("Mismatching dynamic type.");
    } else if (auto *p = dynamic_cast<bar_class2 *>(this)) {
        return p->fun();
    }

    assert(false); //should never get here, but compiler doesn't know that
}

如果你想要主函数,我写了一个complete sample。

【讨论】:

    【解决方案3】:

    回答您的问题:不,如果不确定返回类型,后期绑定是不可能的。 ...至少不是以合理的方式,请参阅user2079303's great counter-example。但是……

    您可以使用关键字virtual 将您的代码(例如)更改为以下内容,并将返回类型(例如)等于void:

    class foo 
    {
    public:
        virtual void fun(std::ostream& out) {
            out << "in foo" << std::endl;
        }
    };
    

    所以你可以稍后决定输出类型:

    class intFoo: public foo 
    {
    public:
        void fun(std::ostream& out)  {
            // output an int
            out << "in bar_class1. data: " << data << endl;
        }
        int data;
    };
    
    class floatFoo: public foo 
    {
    public:
        void fun(std::ostream& out)  {
            // output a float 
            out << "in bar_class2. data: " << data << endl;
        }
        float data;
    };
    

    为简洁起见,我双重使用输出流 - 现在是函数 fun() 的参数 - 用于演示派生类的类型相关部分的函数。在您的应用程序中,参数可能是另一种更有用的类型。

    【讨论】:

    • 这将导致错误,因为bar_class2::fun 覆盖它,但返回类型不兼容。
    • 对不起,我忽略了这个细节,现在已经更正了。
    • 这也没有解决 Sagar 的问题。正如 Sagar 在对原始问题的评论中所说,缺少 return 语句只是一个疏忽,同时创建了一个最小的问题示例。Sagar 问题的重点是在继承层次结构中需要不同的返回类型。
    • @jamessan 但这是不可能的 - 使用后期绑定。
    • 当然,但这不会改变 Sagar 的要求。更改代码的意图以提供答案并不能解决问题。
    【解决方案4】:

    函数 fun 不是虚函数,因为您没有使用关键字“virtual”来装饰它。因此,编译将确定在编译时调用哪个函数。所以,没有办法告诉编译器调用另一个函数,因为编译器会使用它的静态类型,即变量定义类型——foo *。

    【讨论】:

      猜你喜欢
      • 2010-12-13
      • 1970-01-01
      • 2017-06-25
      • 1970-01-01
      • 2012-02-09
      • 2010-12-26
      • 1970-01-01
      • 1970-01-01
      • 2014-10-28
      相关资源
      最近更新 更多