Режимы видимости в C ++ с примерами
Когда базовый класс является производным от производного класса с помощью наследования, доступность базового класса производным классом контролируется режимами видимости. Производный класс не наследует доступ к закрытым членам данных. Однако он наследует полный родительский объект, который содержит все закрытые члены, объявленные этим классом.
// C++ implementation to show// Visibility modes #include <bits/stdc++.h>using namespace std; // Base class// Class A will be inheritedclass A {public : int x; protected : int y; private : int z;}; // Derived class// Class B will inherit Class Aclass B : public A {}; // main functionint 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 и использовать его.
Типы режимов видимости:
Есть три типа режимов видимости:
- Режим публичной видимости: если мы производим подкласс от общедоступного базового класса. Тогда открытый член базового класса станет общедоступным в производном классе, а защищенные члены базового класса станут защищенными в производном классе.
// C++ implementation to show// Public Visibility mode#include <bits/stdc++.h>usingnamespacestd;// Base class// Class A will be inheritedclassA {public:intx;protected:inty;private:intz;};// Derived class// Class B will inherit Class A// using Public Visibility modeclassB :publicA {};// main functionintmain(){B b;// x is public and it will remain public// so its value will be printedcout << bx << endl;// y is protected and it will remain protected// so it will give visibility errorcout << by << endl;// z is not accessible from B as// z is private and it will remain private// so it will give visibility errorcout << 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; ^ - Режим защищенной видимости: если мы производим подкласс от защищенного базового класса. Тогда как открытый член, так и защищенные члены базового класса станут защищенными в производном классе.
// C++ implementation to show// Protected Visibility mode#include <bits/stdc++.h>usingnamespacestd;// Base class// Class A will be inheritedclassA {public:intx;protected:inty;private:intz;};// Derived class// Class B will inherit Class A// using Protected Visibility modeclassB :protectedA {};// main functionintmain(){B b;// x is public and it will become protected// so it will give visibility errorcout << bx << endl;// y is protected and it will remain protected// so it will give visibility errorcout << by << endl;// z is not accessible from B as// z is private and it will remain private// so it will give visibility errorcout << 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; ^ - Режим приватной видимости: если мы производим подкласс от частного базового класса. Тогда как открытый, так и защищенный члены базового класса станут частными в производном классе.
// C++ implementation to show// Private Visibility mode#include <bits/stdc++.h>usingnamespacestd;// Base class// Class A will be inheritedclassA {public:intx;protected:inty;private:intz;};// Derived class// Class B will inherit Class A// using Private Visibility modeclassB :privateA {};// main functionintmain(){B b;// x is public and it will become private// so it will give visibility errorcout << bx << endl;// y is protected and it will become private// so it will give visibility errorcout << by << endl;// z is not accessible from B as// z is private and it will remain private// so it will give visibility errorcout << 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 inheritedclass BaseClass { // Public memberspublic : int a; // Protected membersprotected : int b; int c; // Private membersprivate : int d; int e;}; // BaseClass will be inherited as private// to change all the members to private firstclass DerivedClass : private BaseClass { // Now change the visibility of b // from private to publicpublic : using BaseClass::b;}; // main functionint 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;
^