Режимы видимости в C ++ с примерами

Опубликовано: 4 Декабря, 2021

Когда базовый класс является производным от производного класса с помощью наследования, доступность базового класса производным классом контролируется режимами видимости. Производный класс не наследует доступ к закрытым членам данных. Однако он наследует полный родительский объект, который содержит все закрытые члены, объявленные этим классом.

// C++ implementation to show
// Visibility modes
#include <bits/stdc++.h>
using namespace std;
// Base class
// Class A will be inherited
class A {
public :
int x;
protected :
int y;
private :
int z;
};
// Derived class
// Class B will inherit Class A
class B : public A {
};
// main function
int main()
{
B b;
// x is public
// so its value will be printed
cout << bx << endl;
// y is protected
// so it will give visibility error
cout << by << endl;
// z is not accessible from B
// so it will give visibility error
cout << bz << endl;
};

Ошибки компиляции:

prog.cpp: В функции int main ():
prog.cpp: 14: 6: ошибка: 'int A :: y' защищен
  int y;
      ^
prog.cpp: 34: 12: ошибка: в этом контексте
  cout << на << endl;
            ^
prog.cpp: 17: 6: ошибка: 'int A :: z' является закрытым
  int z;
      ^
prog.cpp: 37: 12: ошибка: в этом контексте
  cout << bz << endl;
            ^

Что означает видимость в этой программе?

  • Поскольку член «x» в A является общедоступным , его видимость будет открыта для всех. Это означает, что любой класс может получить доступ и использовать этот x. По этой причине в "b.x" нет ошибки.
  • Член «y» в A защищен , его видимость будет только для производного класса. Это означает, что любой производный класс может получить доступ к этому y и использовать его.
  • Элемент z в A является частным , его видимость не будет открыта для других классов. Это означает, что любой производный класс не может получить доступ к этому z и использовать его.

Типы режимов видимости:

Есть три типа режимов видимости:

  1. Режим публичной видимости: если мы производим подкласс от общедоступного базового класса. Тогда открытый член базового класса станет общедоступным в производном классе, а защищенные члены базового класса станут защищенными в производном классе.
    // C++ implementation to show
    // Public Visibility mode
    #include <bits/stdc++.h>
    using namespace std;
    // Base class
    // Class A will be inherited
    class A {
    public :
    int x;
    protected :
    int y;
    private :
    int z;
    };
    // Derived class
    // Class B will inherit Class A
    // using Public Visibility mode
    class B : public A {
    };
    // main function
    int main()
    {
    B b;
    // x is public and it will remain public
    // so its value will be printed
    cout << bx << endl;
    // y is protected and it will remain protected
    // so it will give visibility error
    cout << by << endl;
    // z is not accessible from B as
    // z is private and it will remain private
    // so it will give visibility error
    cout << bz << endl;
    };

    Ошибки компиляции:

    prog.cpp: В функции int main ():
    prog.cpp: 14: 9: ошибка: 'int A :: y' защищен
         int y;
             ^
    prog.cpp: 37: 15: ошибка: в этом контексте
         cout << на << endl;
                   ^
    prog.cpp: 17: 9: ошибка: 'int A :: z' является закрытым
         int z;
             ^
    prog.cpp: 42: 15: ошибка: в этом контексте
         cout << bz << endl;
                   ^
    
  2. Режим защищенной видимости: если мы производим подкласс от защищенного базового класса. Тогда как открытый член, так и защищенные члены базового класса станут защищенными в производном классе.
    // C++ implementation to show
    // Protected Visibility mode
    #include <bits/stdc++.h>
    using namespace std;
    // Base class
    // Class A will be inherited
    class A {
    public :
    int x;
    protected :
    int y;
    private :
    int z;
    };
    // Derived class
    // Class B will inherit Class A
    // using Protected Visibility mode
    class B : protected A {
    };
    // main function
    int main()
    {
    B b;
    // x is public and it will become protected
    // so it will give visibility error
    cout << bx << endl;
    // y is protected and it will remain protected
    // so it will give visibility error
    cout << by << endl;
    // z is not accessible from B as
    // z is private and it will remain private
    // so it will give visibility error
    cout << bz << endl;
    };

    Ошибки компиляции:

    prog.cpp: В функции int main ():
    prog.cpp: 11: 9: ошибка: 'int A :: x' недоступен
         int x;
             ^
    prog.cpp: 33: 15: ошибка: в этом контексте
         cout << bx << endl;
                   ^
    prog.cpp: 14: 9: ошибка: 'int A :: y' защищен
         int y;
             ^
    prog.cpp: 37: 15: ошибка: в этом контексте
         cout << на << endl;
                   ^
    prog.cpp: 17: 9: ошибка: 'int A :: z' является закрытым
         int z;
             ^
    prog.cpp: 42: 15: ошибка: в этом контексте
         cout << bz << endl;
                   ^
    
  3. Режим приватной видимости: если мы производим подкласс от частного базового класса. Тогда как открытый, так и защищенный члены базового класса станут частными в производном классе.
    // C++ implementation to show
    // Private Visibility mode
    #include <bits/stdc++.h>
    using namespace std;
    // Base class
    // Class A will be inherited
    class A {
    public :
    int x;
    protected :
    int y;
    private :
    int z;
    };
    // Derived class
    // Class B will inherit Class A
    // using Private Visibility mode
    class B : private A {
    };
    // main function
    int main()
    {
    B b;
    // x is public and it will become private
    // so it will give visibility error
    cout << bx << endl;
    // y is protected and it will become private
    // so it will give visibility error
    cout << by << endl;
    // z is not accessible from B as
    // z is private and it will remain private
    // so it will give visibility error
    cout << bz << endl;
    };

    Ошибки компиляции:

    prog.cpp: В функции int main ():
    prog.cpp: 11: 9: ошибка: 'int A :: x' недоступен
         int x;
             ^
    prog.cpp: 33: 15: ошибка: в этом контексте
         cout << bx << endl;
                   ^
    prog.cpp: 14: 9: ошибка: 'int A :: y' защищен
         int y;
             ^
    prog.cpp: 37: 15: ошибка: в этом контексте
         cout << на << endl;
                   ^
    prog.cpp: 17: 9: ошибка: 'int A :: z' является закрытым
         int z;
             ^
    prog.cpp: 42: 15: ошибка: в этом контексте
         cout << bz << endl;
                   ^
    

Как изменить режим видимости после наследования?

После наследования базового класса с помощью определенного режима видимости члены автоматически изменят его видимость, как указано выше. Но для того, чтобы изменить видимость после этого наследования, нам нужно сделать это вручную.

Синтаксис:

<visibility_mode>:
    используя base :: <member>;

Например:

// чтобы изменить видимость x на общедоступную
<общедоступный>:
    используя base :: <x>;

Пример: рассмотрим базовый класс, содержащий открытый член «a», защищенные члены «b» и «c» и частные члены «d» и «e». Программа ниже объясняет, как изменить видимость символа «b» с защищенного на общедоступный.

// C++ implementation to show how to
// change the Visibility modes
#include <bits/stdc++.h>
using namespace std;
// Base class
// Class A will be inherited
class BaseClass {
// Public members
public :
int a;
// Protected members
protected :
int b;
int c;
// Private members
private :
int d;
int e;
};
// BaseClass will be inherited as private
// to change all the members to private first
class DerivedClass : private BaseClass {
// Now change the visibility of b
// from private to public
public :
using BaseClass::b;
};
// main function
int main()
{
DerivedClass derivedClass;
// d must be private and
// hence generate visibility error
cout << derivedClass.d << endl;
// b must be now pubic and hence should
// not generate visibility error
cout << derivedClass.b << endl;
return 0;
};

Ошибки компиляции:

prog.cpp: В функции int main ():
prog.cpp: 22: 9: ошибка: 'int BaseClass :: d' является частным
     int d;
         ^
prog.cpp: 47: 26: ошибка: в этом контексте
     cout << производныйClass.d << endl;
                          ^
Хотите узнать о лучших видео и практических задачах, ознакомьтесь с базовым курсом C ++ для базового и продвинутого уровня C ++ и курсом C ++ STL для базового уровня плюс STL. Чтобы завершить подготовку от изучения языка к DS Algo и многому другому, см. Полный курс подготовки к собеседованию .
C++