防止在 C++ 中调用基本赋值运算符

Prevent call to base assignment operator in C++

我的图书馆里有这两个 class:

class Base {
    int _handler;
protected:
    Base() = default;

    Base& operator=(int h) {
        this->_handler = h;
        return *this;
    }
};

class Derived : public Base {
protected:
    Derived() = default;

    void initialize() {
        this->Base::operator=(12345); // internal stuff
    }
};

Derived class 可供用户继承。他应该这样做:

class User_Class : public Derived {
    void foo() {
        this->initialize();
    }
};

但是,他却这样做了:

class User_Class : public Derived {
    void foo() {
        this->Base::operator=(999); // no, you broke it!
    }
};

如何防止调用 Base 赋值运算符?

当我将 header 更改为此

class Derived : private Base

编译器立即用 "cannot access inaccessible member declared in class 'Base'" 阻止对 operator= 的调用,但是调用 initialize 的代码正常工作,因为它是可访问的。

但是,你也应该覆盖Derived中的operator=,让它检查它是否已经被初始化。不要让客户 class 处理内部簿记。