如何重写模板化子类中的非模板化方法
How to override a non-templated method in a templated subclass
#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
)是一个类。
相关文章:
- 从父类方法返回子类对象
- c++, 在子类中,如何在没有对象的情况下访问父类的方法?
- 将子类方法声明为基类的友元
- 使用模板参数重载C++方法:如何使其适用于模板的子类?
- C++有没有办法强制重写一组方法,如果其中一个方法在子类中具有重写?
- C ++类型特征:确保子类实现方法
- 函数从唯一代码调用正确的子类方法
- Arduino在子类中使用父类方法
- C++强制在子类中实现方法,但具有不同的签名
- 我们可以在没有新实例化的情况下声明一个抽象方法来返回抽象超类中的子类对象吗
- 如何调用传递给 JNI 'jobject' 的 Java 对象的子类/子类的方法
- 将方法参数类型更改为子类中的派生类
- 如果指针的子类的方法对于子类是唯一的,如何访问这些方法?
- C++继承,如何在基类的方法中调用子类的方法?
- 在子类上调用模板化静态方法时获取类的类型名
- 检查子类是否执行了方法重写
- 将"this"从父类方法转换为子类方法是一种好的做法吗?
- 从C++中的父类实例访问子类方法
- 基类中的虚拟方法和子类中的非 Virtula 方法.仍然如何调用子类方法,即使它是非虚拟的
- C ,基础课程如何将子类作为成员包含并调用其方法