📜  公开继承基类,但将一些公共方法设为私有

📅  最后修改于: 2021-05-30 17:33:18             🧑  作者: Mango

在某些情况下,我们想使某些公共基类函数在派生类中成为私有函数。假设基类和子类都具有getter和setter方法

// CPP program to demonstrate that all base
// class public functions become available
// in derived class if we use public inheritance.
#include 
using namespace std;
  
class Base {
    int i;
  
public:
    Base() {}
    void setBaseProperties(int i)
    {
        this->i = i;
    }
    void showBaseProperties()
    {
        std::cout << endl
                  << "i = " << i;
    }
    virtual ~Base() {}
};
  
class Child : public Base {
    int j;
    int k;
  
public:
    void setChildProperties(int i, int j, int k)
    {
        setBaseProperties(i);
        this->j = j;
        this->k = k;
    }
    void showChildProperties()
    {
        showBaseProperties();
        cout << " j = " << j << " k = " << k;
    }
};
  
int main()
{
    Child c;
    c.setChildProperties(1, 2, 3);
  
    // this exposed function is undesirable
    c.setBaseProperties(4); 
  
    c.showChildProperties();
    return 0;
}
输出:
i = 4 j = 2 k = 3

在这里,如果我们需要限制子类对象“ c”对函数“ setBaseProperties”和“ showBaseProperties”的调用。这可以在不覆盖以下函数的情况下实现:

我们使用“使用”语法在派生类范围中重新声明基类函数。我们在派生类的私有部分中执行此操作。

// CPP program to demonstrate that some of
// base class public functions cane be restricted
// in derived class if we re-declare them with 
// "using" in private section of derived class
#include 
using namespace std;
  
class Base {
    int i;
  
public:
    Base() {}
    void setBaseProperties(int i)
    {
        this->i = i;
    }
    void showBaseProperties()
    {
        std::cout << endl
                  << "i = " << i;
    }
    virtual ~Base() {}
};
  
class Child : public Base {
    int j;
    int k;
  
    // Redeclaring scope of base class
    // functions in private section of
    // derived class.
    using Base::showBaseProperties;
    using Base::setBaseProperties;
  
public:
    void setChildProperties(int i, int j, int k)
    {
        setBaseProperties(i);
        this->j = j;
        this->k = k;
    }
    void showChildProperties()
    {
        showBaseProperties();
        cout << " j = " << j << " k = " << k;
    }
};
  
int main()
{
    Child c;
    c.setChildProperties(1, 2, 3);
  
    // if we uncomment this part of code, it causes 
    // compilation error as the function is private 
    // now
    // c.setBaseProperties(4); 
  
    c.showChildProperties();
    return 0;
}
输出:
i = 1 j = 2 k = 3
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”