C ++继承,调用给定的类函数而不是父类?

时间:2015-05-04 23:06:09

标签: c++ inheritance

标题真的很糟糕,想不出怎么说出来,抱歉。

所以说我有以下代码:

com.sun.crypto.provider.GHASH#update(byte[], int, int)

它会打印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,其中大小为64,如果我将该C实例传递给{{1}功能,我希望它打印64。

我有什么方法可以用C ++做到这一点,我是否必须使用模板或一些我不知道的奇特C ++功能?

3 个答案:

答案 0 :(得分:8)

一个单字节补丁:

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

您的版本按值获取参数,这意味着该函数会复制b(副本为A),然后调用副本{{1} }。在此版本中,该函数通过引用获取参数,并调用getSize()自己的b,即getSize()

答案 1 :(得分:1)

你应该使用指针,甚至更好:智能指针!这样,就会调用运行时类型的函数。它是多态性的基本例子。如果你想避免使用指针,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实现的功能。

答案 2 :(得分:0)

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

几乎可以直接使用,只需将你的A级称为A,B和C可以是Square和Triangle。你的DoStuff函数可以获取一个指向Shape的指针,然后你可以传递一个三角形或一个正方形,当你在函数中使用Shape时,它将调用正确的函数。

所以你有(也许你需要让成员公开,我想):

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);
}
相关问题