C++ 中私有與受保護之間的區別


在這篇文章中,我們將瞭解 C++ 中私有且受保護的訪問修飾符之間的區別。

私有訪問修飾符

  • 使用“私有”關鍵字宣告它們,後跟“:”。

  • 無法在類外部訪問它們。

  • “private”關鍵字是一個訪問修飾符,它確保只能由已宣告它們的類成員訪問類中的函式和屬性。

  • 只有成員函式或友元函式才能訪問標記為“private”的資料。

示例

 線上演示

#include <iostream>
using namespace std;
class base_class{
   private:
   string my_name;
   int my_age;
   public:
   void getName(){
      cout << "Enter the name... ";
      cin >> my_name;
      cout << "Enter the age... ";
      cin >> my_age;
   }
   void printIt(){
      cout << "The name is : " << my_name << endl;
      cout << "The age is: " << my_age << endl;
   }
};
int main(){
   cout<<"An object of class is created"<< endl;
   base_class my_instance;
   my_instance.getName();
   my_instance.printIt();
   return 0;
}

輸出

/tmp/u5NtWSnX5A.o
An object of class is created
Enter the name... Jane
Enter the age... 34
The name is : Jane
The age is: 34

受保護的訪問修飾符

  • 保護訪問修飾符類似於私有訪問修飾符。

  • 使用“protected”關鍵字宣告它們,後跟“:”。

  • 宣告為“Protected”的類成員無法在類外部訪問。

  • 可以在宣告它們的類中訪問它們。

  • 它們也可以由父類包含“受保護”成員的派生類訪問。

  • 在使用繼承概念時使用它們。

示例

 線上演示

#include <iostream>
using namespace std;
class base_class{
   private:
   string my_name;
   int my_age;
   protected:
   int my_salary;
   public:
   void getName(){
      cout << "Enter the name... ";
      cin >> my_name;
      cout << "Enter the age... ";
      cin >> my_age;
   }
   void printIt(){
      cout << "The name is : " << my_name << endl;
      cout << "The age is: " << my_age << endl;
   }
};
class derived_class : public base_class{
   private:
   string my_city;
   public:
   void set_salary(int val){
      my_salary = val;
   }
   void get_data_1(){
      getName();
      cout << "Enter the city... ";
      cin >> my_city;
   }
   void print_it_1(){
      cout << "The salary is: " << my_salary << endl;
      printIt();
      cout << "The city is: " << my_city << endl;
   }
};
int main(){
   cout<<"Instance of derived class is being created.."<<endl;
   derived_class my_instance_2 ;
   my_instance_2.set_salary(100);
   my_instance_2.get_data_1();
   my_instance_2.print_it_1();
   return 0;
}

輸出

/tmp/u5NtWSnX5A.o
Instance of derived class is being created..
Enter the name... Jane
Enter the age... 23
Enter the city... NewYork
The salary is: 100
The name is : Jane
The age is: 23
The city is: NewYork

更新於: 23-Mar-2021

1K+ 次瀏覽

開啟你的 職業生涯

完成本課程獲得認證

開始吧
廣告