假设我有这个:
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 个操作它的函数传递一个类。
最佳答案
您在这里所做的事情有时会严重失败,因为派生类的大小大于基类,并且您在基类结束后编写。上面的写操作会覆盖属于另一个对象的内存。 您可以在基类中有一个 SetValue() 方法,并在派生类中实现它。
关于c++ - 通过将基类强制转换为派生类并设置数据来扩展基类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20198949/