覆盖返回typename T的方法不起作用
Overriding a method returning typename T does not work
#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
是声明的,但没有定义。
相关文章:
- 基本加密和解密方法不起作用 C++ 11.
- 结构/方法不起作用
- 将字符数组设置为彼此相等的方法不起作用
- ConvertToReferencePoint 方法不起作用,获取作业参数的 NULL (HyperV 2016)
- 为什么方法不起作用?
- C boost :: bimap insert()方法不起作用
- 为什么我的将向量保存到文件然后再次读出的方法不起作用?
- 为什么这种交换方法不起作用
- Qt. 方法显示文本() 如果我在 QStyledItemDelegate 中定义了 paint() 方法不起作用
- 非递归二进制树插入()方法不起作用
- C++中的Friend方法不起作用
- 为什么这种删除文件夹中文件的方法不起作用?
- 二叉树递归插入方法不起作用
- CGI POST方法不起作用
- 为什么我的 pow 方法不起作用?
- 类方法不起作用
- 使用ctypes从Python调用C++方法不起作用
- C++虚拟方法不起作用
- 为什么用double&&初始化对象方法不起作用?
- 使用虚拟重写基类方法不起作用