C ++调用正确的虚函数

时间:2015-06-19 09:49:48

标签: c++ templates virtual-functions

我遇到以下情况的问题:

 template<class T>
class A {
public: virtual int  f() { return 1; }
};

class BaseA : public A<BaseA> {};
class DerivedA : public BaseA, public A<DerivedA> {};

当我这样做时:

 BaseA* b1 = new DerivedA;
b1->f();

它调用A<BaseA>::f()而不是A<DerivedA>::f(),我不知道如何修复它。

2 个答案:

答案 0 :(得分:1)

来自OP的其他信息:这是一个家庭作业问题,可以自由更改班级A,但无法更改班级BaseADerivedA

以下是一个解决方案,基于虚拟继承层次中的支配

#include <iostream>
#include <typeinfo>
using namespace std;

struct BaseA;

struct I
{
    virtual auto  f()
        -> int = 0;
};

template<class T>
class A
    : public virtual I
{
public:
    virtual auto  f()
        -> int override
    { cout << typeid( T ).name() << '\n'; return 1; }
};

template<>
class A<BaseA>: public virtual I {};

class BaseA : public A<BaseA> {};
class DerivedA : public BaseA, public A<DerivedA> {};

auto main() -> int
{
    BaseA* b1 = new DerivedA;
    b1->f();
}

答案 1 :(得分:0)

以下程序从derivedA调用f(输出:f in derived)。工作正常..这里有什么不对吗?

#include <iostream>
using namespace std;

template<class T>
class A
{
  public:
   virtual int f()
   {
       return 1;
   }
};

class BaseA : public A<BaseA>
{
  public:
  virtual int f()
  {
   cout << "f in base" << endl;
   return 1;
  }
};

class DerivedA :  public BaseA, public A<DerivedA>
{
   public:
   int f()
   {
       cout << "f in derived" << endl;
       return 1;
    }
};

main() {
    BaseA* b1 = new DerivedA;
    b1->f();
}