C++/Class/Protected

Материал из C\C++ эксперт
Перейти к: навигация, поиск

Demonstrate protected members.

 
 
#include <iostream> 
using namespace std; 
 
class BaseClass { 
protected: 
  int i, j;             // private to BaseClass, but accessible to D 
public: 
  void set(int a, int b) { 
     i = a; 
     j = b; 
  } 
  void show() { 
     cout << i << " " << j << endl; 
  } 
}; 
 
class DerivedClass : public BaseClass { 
  int k; 
public: 
  void setk() {         // DerivedClass may access BaseClass"s i and j 
     k = i * j; 
  } 
 
  void showk() { 
     cout << k << endl; 
  } 
}; 
 
int main() 
{ 
  DerivedClass object; 
 
  object.set(2, 3);     // OK, set() is public in BaseClass 
  object.show();        // OK, show is public BaseClass 
 
  object.setk(); 
  object.showk(); 
 
  return 0; 
}


Inheriance for protected member

 
#include <iostream>
using namespace std;
class BaseClass {
protected:
  int i, j;
public:
  void set(int a, int b) { 
     i = a; 
     j = b; 
  }
  void show() { 
     cout << i << " " << j << endl; 
  }
};
// i and j inherited as protected.
class DerivedClass1 : public BaseClass {
  int k;
public:
  void setk() { 
     k = i * j; 
  }
  void showk() { 
   
     cout << k << endl; 
 
  }
};
// i and j inherited indirectly through DerivedClass1.
class DerivedClass2 : public DerivedClass1 {
 
  int m;
public:
  void setm() { 
     m = i - j; 
  }
  void showm() { 
     cout << m << endl; 
  }
};
int main()
{
  DerivedClass1 object1;
  DerivedClass2 object2;
  object1.set(2, 3);
  object1.show();
  object1.setk();
  object1.showk();
  object2.set(3, 4);
  object2.show();
  object2.setk();
  object2.setm();
  object2.showk();
  object2.showm();
  return 0;
}


Inherit base as protected

 
#include <iostream>
using namespace std;
class BaseClass {
protected:
  int i, j;                    // private to BaseClass, but accessible by DerivedClass
public:
  void setij(int a, int b) { 
     i = a; 
     j = b; 
  }
  void showij() { 
     cout << i << " " << j << endl; 
  }
};

class DerivedClass : protected BaseClass{               // Inherit BaseClass as protected.
  int k;
public:
  void setk() {    
     setij(10, 12); 
     k = i * j; 
  }
  void showall() { 
     cout << k << " "; 
     showij(); 
  }
};
int main()
{
  DerivedClass ob;
  ob.setk();                   // public member of DerivedClass
  ob.showall();                // public member of DerivedClass
  return 0;
}


protected inheritance

  
#include <iostream>
using namespace std;
class base 
{
 protected:
   int i, j;
 public:
   void setij(int a, int b){
     i=a; 
     j=b;
   }
   void showij(void) {cout << i << " " << j << endl;}
 };
class derived : protected base 
{
 private:
   int k;
 public:
   void setk(void){
     setij(10,12); 
     k = i * j;
   }
   void showall(void){
     cout << k << " "; 
     showij();
   }
};
int main(void){
   derived object;
   object.setk();
   object.showall();
}