我正在尝试弄清楚如何更改 vector 类型。类 foo 代表数据结构,被许多算法使用。然而,新的要求是将上次处理算法的结果存储为 float 据。下面的代码显示了问题的最低版本
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class foo{
protected:
vector<int> a;
public:
virtual void print(){
cout<<"foo type of " <<sizeof(a[0])<<endl;
};
};
class bar: public foo
{
vector<double> a;
};
int main()
{
foo f;
f.print();
bar b;
b.print();
return 0;
}
“程序”的输出是:
foo type of 4
foo type of 4
我的期望是:
foo type of 4
foo type of 8
那么如何在不大量重复代码的情况下得到这样的结果。 我期待着您的回音。
最佳答案
当谈到编译时已知的类型时,静态多态性(使用模板)通常比运行时多态性(使用虚函数)更强大。
您的期望是基于错误的假设,即虚函数在派生类中隐式重新定义。由于您没有覆盖虚函数,因此您不会从它的虚函数中受益,您也可以省略 virtual
关键字。因为它是在基类中定义的,所以它总是引用基类中的a
成员。
MPI_What 的答案显示了一种使用模板的可能方法。 编辑:对于基于运行时多态性的解决方案,您可以将静态多态性与动态多态性结合起来,从而产生一种称为类型删除的技术:
struct Base
{
virtual void print() const = 0;
}
template <typename T>
struct Derived : Base
{
virtual void print() const
{
...
}
std::vector<T> a;
};
关于c++ - 改变成员 vector 的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33080699/