protected 訪問修飾符與 private 訪問修飾符類似,不同之處在於聲明為 Protected 的類成員在類外部不可訪問,但可以被該類的任何子類(派生類)訪問。
例子:
CPP
// C++ program to demonstrate
// protected access modifier
#include <bits/stdc++.h>
using namespace std;
// base class
class Parent {
// protected data members
protected:
int id_protected;
};
// sub class or derived class
class Child : public Parent {
public:
void setId(int id)
{
// Child class is able to access the inherited
// protected data members of the base class
id_protected = id;
}
void displayId()
{
cout << "id_protected is: "
<< id_protected << endl;
}
};
// main function
int main()
{
Child obj1;
// member function of the derived class can
// access the protected data members of the base class
obj1.setId(81);
obj1.displayId();
return 0;
}
輸出:
id_protected is: 81
聲明為 private 的類成員隻能由類內部的函數訪問。它們不允許被類外部的任何對象或函數直接訪問。隻有成員函數或友元函數才允許訪問類的私有數據成員。
例子:
CPP
// C++ program to demonstrate private
// access modifier
#include <iostream>
using namespace std;
class Circle {
// private data member
private:
double radius;
// public member function
public:
void compute_area(double r)
{
// member function can access private
// data member radius
radius = r;
double area = 3.14 * radius * radius;
cout << "Radius is: " << radius << endl;
cout << "Area is: " << area;
}
};
// main function
int main()
{
// creating object of the class
Circle obj;
// trying to access private data member
// directly outside the class
obj.compute_area(1.5);
return 0;
}
輸出:
Radius is: 1.5 Area is: 7.065
私有和受保護之間的區別
私人的 | 受保護 |
---|---|
聲明為 private 的類成員隻能由類內部的函數訪問。 | 受保護的訪問修飾符與私有訪問修飾符類似。 |
私人成員將實施細節保留在程序中。 | 受保護的成員增強了對派生類的訪問。 |
隻有成員函數或友元函數才允許訪問類的私有數據成員。 | 聲明為 Protected 的類成員在類外部不可訪問,但可以由該類的任何子類(派生類)訪問。 |
私有成員不在類中繼承。 | 受保護的成員在類中繼承。 |
相關用法
- C++ Power用法及代碼示例
- C++ cos()用法及代碼示例
- C++ sin()用法及代碼示例
- C++ asin()用法及代碼示例
- C++ atan()用法及代碼示例
- C++ atan2()用法及代碼示例
- C++ acos()用法及代碼示例
- C++ tan()用法及代碼示例
- C++ sinh()用法及代碼示例
- C++ ceil()用法及代碼示例
- C++ tanh()用法及代碼示例
- C++ fmod()用法及代碼示例
- C++ acosh()用法及代碼示例
- C++ asinh()用法及代碼示例
- C++ floor()用法及代碼示例
- C++ atanh()用法及代碼示例
- C++ log()用法及代碼示例
- C++ trunc()用法及代碼示例
- C++ round()用法及代碼示例
- C++ lround()用法及代碼示例
- C++ llround()用法及代碼示例
- C++ rint()用法及代碼示例
- C++ lrint()用法及代碼示例
- C++ log10()用法及代碼示例
- C++ modf()用法及代碼示例
注:本文由純淨天空篩選整理自Code_r大神的英文原創作品 Difference between Private and Protected in C++ with Example。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。