【问题标题】:C++ abstract class inheritance virtual functionC++抽象类继承虚函数
【发布时间】:2023-03-14 06:06:01
【问题描述】:

我有一个抽象基类,其中包含一些属性或成员元素以及一些公共函数和一个公共纯虚函数。在抽象类的派生类中,我想(a)访问抽象基类的成员作为私有成员,(b)公共函数和定义的纯虚函数保持公共。有没有办法做到这一点?也就是说,要实现这一点,派生的 AbstractBase 和 yyyy 访问说明符的 xxxx 应该是什么?

#include <iostream>

class AbstractBase {
 xxxx: <-- // protected/private/public?
  std::string baseprivate1;

 public:
  virtual void set_privates() = 0;
  void print() { std::cout << baseprivate1 << std::endl; }
  void foo() { // some definition here }
};

class Derived : yyyy AbstractBase {  <--- //public/protected/private? 
 private:
  std::string derivedprivate1;

 public:
  void set_privates() {
    // I want this baseprivate1 to be private in derived class as well.
    // When I choose xxxx as protected and yyyy as public, the baseprivate1 is protected. 
    this->baseprivate1 = "Base private1";
    this->derivedprivate1 = "Derived private1";
  }
  void print() {
    AbstractBase::print();
    std::cout << this->derivedprivate1;
  }
  // When I choose xxxx as protected and yyyy as protected
  // foo becomes protected and unable to call from outside
  // I want the foo of abstract base to be public here as well. 
};

int main(int argc, char *argv[]){
    Derived d;
    d.set_privates();
    d.print();
    d.foo(); // I should be able to call foo of abstract base class
}

它可能会被混淆为Difference between private, public, and protected inheritance 的重复。如果您将 xxxx 保持为受保护而 yyyy 保持为公共,则 baseprivate1 将在 Derived 中受到保护并且不再是私有的。或者,如果 xxxx 是 public/protected 并且 yyyy 是私有的,则派生的函数将变为私有。

【问题讨论】:

  • 简答:xxxx - 受保护,yyyy - 公共
  • @slava 使 baseprivate1 在派生而不是私有中受到保护。
  • @RamakrishnanKannan 您的数据应提供尽可能低的访问权限,在这种情况下,protected 是必要的,无论您是否想要。
  • 你想要的建议了一个可能没有充分考虑的班级策略。我怀疑是XY problem。

标签: c++ oop


【解决方案1】:

实现您想要的一种方法是在您的 Derived 类上使用 AbstractBase 的私有继承。然后,您可以在 Derived 类的公共访问说明符下使用 using 声明公开 AbstractBase 的一些方法。

#include <iostream>

class AbstractBase {
    public:
        std::string baseprivate1;

        virtual void set_privates() = 0;
        void print() { std::cout << baseprivate1 << std::endl; }
        void foo() { /* some definition here */ }
};

class Derived : private AbstractBase { // use private inheritance on AbstractBase
    private:
        std::string derivedprivate1;

    public:
        // expose AbstractBase's methods with using-declarations
        using AbstractBase::foo;
        using AbstractBase::print;

        void set_privates() {
            this->baseprivate1 = "Base private1";
            this->derivedprivate1 = "Derived private1";
        }

        void print() {
            AbstractBase::print();
            std::cout << this->derivedprivate1 << std::endl;;
        }
};

int main(int argc, char *argv[]){
    Derived d;
    d.set_privates();
    d.print();
    d.foo();
    return 0;
}

【讨论】:

    猜你喜欢
    • 2020-06-19
    • 2015-06-23
    • 2014-08-16
    • 2011-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-23
    相关资源
    最近更新 更多