-4
#include <iostream>
#include <string>

using namespace std;

template <typename T>
class A
{
public:
    A()
    {
        OverrideMe();
    }
    virtual ~A(){};

    virtual T OverrideMe()
    {
        throw string("A.OverrideMe called");
    }

protected:

    T member;
};

class B : public A<double>
{
public:
    B(){};
    virtual ~B(){};

    virtual double OverrideMe()
    {
        throw string("B.OverrideMe called");
    }
};

int main()
{
    try
    {
        B b;
    }
    catch(string s)
    {
        cout << s << endl; //this prints: A.OverrideMe called
    }
    return 0;
}
4

2 回答 2

1

您可以覆盖模板基类中的方法,如下例所示:

#include <iostream>
template <typename T> struct Foo
{
  virtual T foo() const {
    std::cout << "Foo::foo()\n";
    return T();
  }
};

struct Bar : Foo<double>
{
  virtual double foo() const {
    std::cout << "Bar::foo()\n";
    return 3.14;
  }
};

int main(){
  Bar b;
  double x = b.foo();
}

输出:

酒吧::foo()

于 2013-04-19T06:27:21.000 回答
0

我怀疑(出乎意料)您的类型T已声明但未定义。

于 2013-04-19T06:32:07.213 回答