C ++抽象类继承虚拟函数

时间:2018-11-30 14:53:58

标签: c++ oop

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

#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将在“派生”中受到保护,并且不再是私有的。另外,如果xxxx为public / protected,而yyyy为private,则派生函数将变为private。

1 个答案:

答案 0 :(得分: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;
}