假设我有这样的:通过它铸造派生并设置数据扩展基类
class Base {
public:
int a;
Base() : a(5) {}
};
template<class T>
class Derived : public Base {
public:
T value;
};
以下作品中的代码,但我想知道什么可以使用这种方法的挑战:
Base * base = new Base;
Derived<int> * derived = static_cast<Derived<int>*>(base);
derived->value = 5;
Derived<String> * derived1 = static_cast<Derived<String>*>(base);
derived1->value = "test";
Derived<String> * newderived = static_cast<Derived<String>*>(base);
std::cout << newderived->value;
Derived<int> * newderived1 = static_cast<Derived<int>*>(base);
std::cout << newderived1->value;
//Output: test1
或者我怎样才能以不同的,更安全的方式实现这样的事情。我想通过5个函数传递一个类来处理它。
简单的解决方案,因为他们在c + +书籍编写,大多是好的。我建议你从简单的,基于继承的,无模板的最小示例开始。试试这个,再次问我们,_that_有什么问题。 – peterh
“作品”在这里似乎有点夸大其辞。您正在覆盖未分配的内存,这会在程序的某个稍后阶段导致未指定但可能导致灾难性的问题。 (尝试使用valgrind获取更多详细信息。) – rici
代码具有未定义的行为,如果它对您有用,那是因为您很不幸。 – john