C 继承,调用给定类功能而不是其父

C++ inheritance, calling the given classes function instead of its parent?

本文关键字:功能 继承 调用      更新时间:2023-10-16

真的很糟糕的标题,无法想到如何言语,对不起。

所以说我有以下代码:

class A {
    virtual int getSize() {
        return 0;
    }
}
class B : public A {
    int getSize() {
        return 32;
    }
}
void doStuff(A a) {
   std::cout << a.getSize() << std::endl;
}
int main() {
   B b;
   doStuff(b);
}

它将打印出0,但是我希望它打印出32。换句话说,我想将其通过类,然后打印出该类功能,因此我可以创建一个C,其中大小为64,如果我将该C实例传递给doStuff函数,我希望它可以打印64。

有什么办法可以在C 中执行此操作?

一个字节补丁:

void doStuff(A &a) {
  std::cout << a.getSize() << std::endl;
}

您的版本按值进行参数,这意味着该函数制作了b的副本(A的副本),然后调用该副本的getSize()。在此版本中,该函数通过参考获取参数,并调用bgetSize(),即B::getSize()

您应该使用指针,甚至更好:智能指针!这样,调用运行时类型的功能。这是多词主义的基本例子。如果您想避免指针,Beta的切片方法同样有效。

#include <iostream>
#include <memory>
class A {
    virtual int getSize() {
        return 0;
    }
}
class B : public A {
    virtual int getSize() {
        return 32;
    }
}
void doStuff(std::shared_ptr<A> a) {
   std::cout << a->getSize() << std::endl;
}
int main() {
   std::shared_ptr<A> b(new B());
   doStuff(b); // Will output '32'.
}  

这应该正确调用b。

实现的函数

切片对象是一种方法,此外,我认为您认为您在C 中非常直接地使用多态性。http://www.cplusplus.com/doc/tutorial/polymorphism/

这几乎是立即适用的,只需称您的班级形状,B和C可能是正方形和三角形。您的dostuff函数可以将指针置于形状,然后可以将其传递给三角形或正方形,当您尊重该功能中的形状时,它将调用正确的函数。

所以您将拥有(我认为您需要公开会员):

class A {
public:
    virtual int getSize() {
        return 0;
    }
};
class B : public A {
public:
    int getSize() {
        return 32;
    }
};
void doStuff(A* a) {
    std::cout << a->getSize() << std::endl;
}
int main() {
    B b;
    doStuff(&b);
}