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

时间:2017-04-14 14:22:08

标签: c++ inheritance assignment-operator

我的库里有这两个类:

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 User_Class : public Derived {
    void foo() {
        this->initialize();
    }
};

但相反,他这样做了:

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

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

1 个答案:

答案 0 :(得分:2)

当我将标题更改为此

class Derived : private Base

编译器立即阻止对operator =的调用"无法访问类' Base'"中声明的不可访问的成员,但是调用initialize的代码正常工作,因为它是可访问的

但是,您还应该在Derived中覆盖operator =,并检查它是否已初始化。不要让客户端类处理内部簿记。