如何重写模板化子类中的非模板化方法

How to override a non-templated method in a templated subclass

本文关键字:方法 子类 何重写 重写      更新时间:2023-10-16
#include <iostream>
using namespace std;
class A{
public:
    virtual int foo() const = 0;
};
template <typename T = int>
class B : public A{
public:
    virtual int foo() const override;
};
int B::foo(){ return 3; }
int main(){
    B<int> b;
    cout << "b.foo()=" << b.foo() << endl;
}

并且我在clang++中遇到以下错误:

clang++ -std=c++11 template_override.cpp
template_override.cpp:16:5: error: expected a class or namespace
int B::foo(){ return 3; }
    ^
1 error generated.

我的问题是,如何在似乎无法使用模板参数的 B 类中实现 B 类中foo()的方法?

我试过把B::foo()做成B<>::foo()但这也不起作用。

您的foo定义缺少const并且不是模板:

   template <typename T>
// ^^^^^^^^^^^^^^^^^^^^^
   int B<T>::foo() const { return 3; }
//      ^^^       ^^^^^^

(现场演示)

请记住,B不是一个类; B是一个类模板。

B<T>(对于某些T)是一个类。