如何从C ++子类中封装用户功能

问题描述 投票:0回答:1

为了解释我的问题,我写了一些例子。

class Product {
public:
  Product(Module& module, Config module_cfg) : module_(module) {
    module_.SetConfig(module_cfg);
  }

  void Work() {
    module_.Work();
  }

private:
  Module& module_;
};

class Module {
public:
  void SetConfig(Config cfg) {
    cfg_ = cfg;
  }

  virtual void Work() = 0;

protected:
  Config cfg_;
};


class ModuleA : public Module {
  void Work() override {
    cfg_.GetSomething(); // use config
  }
};
  1. “产品”的组成部分为“模块”。
  2. “模块”与“配置”一起使用。
  3. “ Module”是“ ModuleA”的父类。

我想封装“ ModuleA”中的“ SetConfig()”方法!

换句话说,有没有办法从继承的类中隐藏用户功能?

c++ oop encapsulation composition
1个回答
0
投票

如果我正确理解了您的问题,您想对任何派生类隐藏基类中的函数,如果是的话,您只需要在派生类中执行此操作:

void SetConfig(Config cfg) = delete;

这会将功能标记为任何派生类都无法访问。

示例:

class A{
public:
    void doSomething(){
    //someting here
    }
};

class B: public A{
    void doSomething() = delete;
};

int main(){
    A a;
    B b;
    a.doSomething(); // will work
    b.doSomething(); // will not work since the function is inaccessible to any derived class
}

[如果您只是希望它在任何派生类中被调用时不执行任何操作,则只需要重写它,以防返回void时将其主体留空,或者如果它返回某些值,则将其保留为空;

© www.soinside.com 2019 - 2024. All rights reserved.