【发布时间】:2015-08-26 03:28:44
【问题描述】:
我有这个代码:
struct All { public: All() {} ~All() {} };
template <typename T>
struct any : public All
{
public:
any() : All() {}
~any() {}
T value;
};
int main()
{
any<int>* a = new any<int>;
a->value = 55;
any<string>* b = new any<string>;
b->value = "Hello World !";
vector<All*> vec;
vec.push_back(a);
vec.push_back(b);
for (int i = 0; i < (int)vec.size(); i++) {
All* tmp = vec[i];
cout << tmp->value << endl; // Error appears here
}
return 0;
}
还有以下错误:
struct 'All' 没有名为 'value' 的成员
而且我不知道如何避免这个错误。似乎在 for 循环中tmp 是一个 All 对象,并且 All 对象没有名为 value 的成员。
他们无法从 All 对象 tmp 访问子结构 (any) 成员变量来避免这个问题并拥有一个功能齐全的通用向量?
【问题讨论】:
-
你可以给
All和any<T>添加一个print虚函数,然后调用它。
标签: c++ templates vector polymorphism generic-programming