我有两个不同的结构体(只是存储数据)共享一些共同的成员的用例,例如
struct Foo {
int i;
int j;
};
struct Bar {
int i;
float f;
};
公共数据可以用基结构体表示,但我想禁用创建基结构体对象的可能性。
如果将构造函数设置为protected,则只有派生类可以访问它:
struct Base {
int i;
protected:
Base() = default;
};
可以人为地在基类中引入抽象方法,例如
struct Base {
int i;
protected:
virtual void blockMe() const = 0;
};
struct Foo : public Base {
int j;
private:
void blockMe() const final {}
};
struct Bar : public Base {
float f;
private:
void blockMe() const final {}
};