简体   繁体   English

通过将基类强制转换为派生并设置数据来扩展基类

[英]extending base class by casting it to derived and setting the data

Assume I have this: 假设我有这个:

class Base {
public:
    int a;
    Base() : a(5) {}
};

template<class T>
class Derived : public Base {
public:
    T value;
};

The code below works but I want to know what can be the challenges of using such approach: 下面的代码有效,但我想知道使用这种方法可能遇到的挑战:

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

Or how can I achieve such thing in a different, safer way. 或者我怎样才能以不同的,更安全的方式实现这样的目标。 I want to pass a class through 5 functions that will manipulate it. 我想通过5个函数传递一个类来操作它。

What you're doing here will fail horribly at some point because the size of the derived class is larger than the base class and you write after the end of the base class. 你在这里做的事情在某些时候会失败,因为派生类的大小比基类大,你在基类结束后写。 The above write operation will overwrite memory that belongs to another object. 上述写操作将覆盖属于另一个对象的内存。 You can have a SetValue() method in the base class and implement it in the derived class. 您可以在基类中使用SetValue()方法,并在派生类中实现它。

The code does not work. 代码不起作用。 All you objects even after casting are still a Base because you constructed them as a base. 即使在施放之后,所有对象仍然是Base因为您将它们构建为基础。 The casts just say: Hey, I know it's a Derived<xxx> , so please just interpret that this way. 演员们只是说:嘿,我知道这是一个Derived<xxx> ,所以请你这样解释。 You don't know this here, in fact you know it is NOT a Derived . 你在这里不知道这一点,事实上你知道它不是Derived

To properly use the objects, you need to create a Derived<xxx> and afterwards cast. 要正确使用这些对象,您需要创建一个Derived<xxx>并随后进行强制转换。 If you use a dynamic_cast here all cases should come back as null as they are Base . 如果你在这里使用dynamic_cast ,所有的情况都应该返回null,因为它们是Base

Given that you wanted to "pass a class through 5 functions" you'd probably want the inverted setup. 鉴于你想“通过5个函数传递一个类”,你可能想要反转设置。 Create Derived<xxx> objects and hold them as a pointer to Base . 创建Derived<xxx>对象并将它们保存为Base的指针。 This works without casting as it should. 这可以在没有应该铸造的情况下工作 Then pass the Base* through your functions. 然后通过你的函数传递Base* Polymorphism will take care that everything works fine. 多态性会照顾一切正常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM