覆盖返回typename T的方法不起作用

Overriding a method returning typename T does not work

本文关键字:方法 不起作用 返回 typename 覆盖      更新时间:2023-10-16
#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;
}

您可以从模板基类重写方法,如下例所示:

#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 ()

我怀疑(出乎意料)您的类型T是声明的,但没有定义。