我可以在父 class 中声明占位符变量,并在子 class 中以不同类型声明它吗?

Can I declare a placeholder variable in parent class, and declare it in different types in child classes?

我能否以某种方式在父级 class 中声明 masiv,以便析构函数可以正常工作,或者我是否需要基本上复制粘贴每个子级的代码 -class?

class Parent{
public:
    int X;
    int Y;
    // I want to declare a placeholder "masiv" here.

    ~Parent()
    {
        for(int i = 0; i < Y; i++)
            delete [] masiv[i];
        delete [] masiv;
    }
};

class Child1 : public Parent {
public:
    int* *masiv;
    // Create method
};

class Child2 : public Parent {
public:
    float* *masiv;
    // Create method
};

注:子classes共享其他方法,都是相同的,但为了简单起见,我没有将它们添加到代码中。但是,我也想将它们添加到父级,但我不能,因为那里没有声明“masiv”。

编辑:模板创造了奇迹!请注意,我对编程还很陌生,直到现在我才知道它们的存在(以及如何使用它们)。

这可以通过模板轻松实现

template<typename T>
class Parent{
public:
    int X;
    int Y;
    // I want to declare a placeholder "masiv" here.
    T** masiv;

virtual ~Parent()  // not an option the virtual destructor
{
    for(int i = 0; i < Y; i++)
      delete [] masiv[i];
    }
    delete [] masiv;
};

class Child : public Parent<int>
{
   // you already have int* masiv here;
}

但是,代码段的编写方式以及您想在父 class 中声明的原因主要是一个糟糕的设计,您将其视为 XY problem

Child1Child2 的“正确”做法是让析构函数清理 那些 [=] 拥有和指定的资源 classes。在这种情况下,是的,这意味着您将拥有相同的 delete[] masiv 行(等),尽管这不是什么大负担。

如果你有很多这些并且真的不想沿着那条路走下去,使用一个可以自我清理的智能指针。

或者,您可以有一个中间基础 class 模板,它拥有(并管理)一个 T** masiv 并派生自 Parent;那么 Child1 将派生自 YourBase<int> 并且 Child2 将派生自 YourBase<float> 使用奇怪的重复模板模式。不过,对于您展示的非常具体的简单示例来说,这太过分了。

class Parent
{
public:
    int X;
    int Y;
    
    // Consider a virtual destructor here; depends what you're doing
};

template <typename T>
class MasivManager : public Parent
{
public:
    T** masiv;
    
    ~MasivManager()
    {
        for (std::size_t i = 0; i < Y; i++)
            delete[] masiv[i];
        delete[] masiv;
    }
};

class Child1 : public MasivManager<int> {};
class Child2 : public MasivManager<float> {};

您可以通过将其设为模板将其交给 Parent 本身:

template <typename T>
class Parent
{
public:
    int X;
    int Y;
    T** masiv;
    
    // Consider making this a virtual destructor; depends what you're doing
    ~Parent()
    {
        for (std::size_t i = 0; i < Y; i++)
            delete[] masiv[i];
        delete[] masiv;
    }
};

class Child1 : public Parent<int> {};
class Child2 : public Parent<float> {};

但是,这是否“有意义”取决于它在您的应用程序中的语义,我们看不到这一点。 Parent 拥有 masiv 合乎逻辑吗?每一种 Parent 都会这样做吗? (根据 XY 居住的地方,我想,“是的”,但只有你能决定。)

你也会失去共同基础 class(因为模板特化是不同的类型),尽管你可能关心也可能不关心。