【问题标题】:Reinitialize all member variables in derived class only仅重新初始化派生类中的所有成员变量
【发布时间】:2016-10-08 13:39:54
【问题描述】:

我有两个班级:

class NonCopyable {
private:
    int key;
protected:
    NonCopyable(const NonCopyable&) = delete;
    NonCopyable& operator = (const NonCopyable &) = delete;
};

class Derived : public NonCopyable {
private:
    std::vector<int> numbers;
    float f;
    int* ptr;
public:
    Derived() : f(5.0f), ptr(nullptr) {}
    ~Derived();
};

现在,我想重新初始化 Derived 类中的所有值并调用适当的析构函数。也就是说,NonCopyable 类不应该被触动,但 Derived 类应该被改变,就好像它是新初始化的一样。

实现这一目标的最简单方法是什么?我试图避免创建一个手动重新初始化每个成员变量的成员函数。


显然,我不能使用以下方法:

Derived d;
// [...] many changes to d
d = Derived();

因为复制构造函数已从 NonCopyable 类中删除,而且如果不是这种情况,它会更改 NonCopyable 的成员变量。

【问题讨论】:

    标签: c++ class initialization


    【解决方案1】:

    如果您将私人数据移动到单独的聚合中,这会变得容易得多:

    struct DerivedData {
        std::vector<int> numbers;
        float f = 5.0;
        int* ptr = nullptr;
    };
    
    class Derived : public NonCopyable {
        DerivedData data;
    public:
        ~Derived();
        void reset() { data = DerivedData(); }
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-30
      相关资源
      最近更新 更多