#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类中实现方法foo()
,似乎我无法使用模板参数?
我已尝试将B::foo()
转换为B<>::foo()
,但这也不起作用。
答案 0 :(得分:3)
您的foo
定义缺少const
并且不是模板:
template <typename T>
// ^^^^^^^^^^^^^^^^^^^^^
int B<T>::foo() const { return 3; }
// ^^^ ^^^^^^
请记住,B
不是一个类; B
是一个类模板。
B<T>
(对于某些T
)是一个类。