虚函数的返回类型不同

ami*_*mit 10 c++ overriding virtual-functions return-type covariant

虚函数的返回类型应与基类或协变中的类型相同.但为什么我们有这个限制?

GMa*_*ckG 13

由于随之而来的废话:

struct foo
{
    virtual int get() const { return 0; }
};

struct bar : foo
{
    std::string get() const { return "this certainly isn't an int"; }
};

int main()
{
    bar b;
    foo* f = &b;

    int result = f->get(); // int, right? ...right?
}
Run Code Online (Sandbox Code Playgroud)

让派生类返回完全不相关的东西是不明智的.


Oli*_*rth 5

因为使用返回值的代码如何应对各种不相关的类型?例如:

class A
{
public:
    virtual float func();
};

class B: public A
{
public:
    virtual char *func();
};

A *p = (some_condition) ? new A() : new B();
p->func();  // Oh no! What is the type?
Run Code Online (Sandbox Code Playgroud)