日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > c/c++ >内容正文

c/c++

C++——类访问修饰符

發布時間:2025/4/16 c/c++ 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 C++——类访问修饰符 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

類訪問修飾符

數據封裝是面向對象編程的一個重要特點,它防止函數直接訪問類類型的內部成員。類成員的訪問限制是通過在類主體內部對各個區域標記?public、private、protected?來指定的。關鍵字?public、private、protected?稱為訪問修飾符。

共有成員(public)

公有成員在程序中類的外部是可訪問的??梢圆皇褂萌魏纬蓡T函數來設置和獲取公有變量的值

#include <iostream>using namespace std ;class Box { public :int Lenth ;int Width ;int Height ;void SetLenth(int len);int GetLenth(void); };int Box::GetLenth(void) {return Lenth ; }void Box::SetLenth(int len) {Lenth = len ; }void main() {// 使用成員函數Box box ;box.SetLenth(2);cout << "Lenth is " <<box.GetLenth()<< endl;// 不使用成員函數box.Lenth = 4 ;cout << "Lenth is " << box.Lenth << endl ; }/* 運行結果 Lenth is 2 Lenth is 4 */

?

私有成員(private)

私有成員變量或函數在類的外部是不可訪問的,甚至是不可查看的。只有類和友元函數可以訪問私有成員。

#include <iostream>using namespace std ;class Box { public :void SetLenth(int len);int GetLenth(void); private:int Lenth ;int Width ;int Height ; };int Box::GetLenth(void) {return Lenth ; }void Box::SetLenth(int len) {Lenth = len ; }void main() {// 使用成員函數Box box ;box.SetLenth(2);cout << "Lenth is " <<box.GetLenth()<< endl;// 不使用成員函數,編譯出錯。 因為Lenth 是私有的。不能在類的外部直接訪問 // box.Lenth = 4 ; // cout << "Lenth is " << box.Lenth << endl ; }

?

保護成員(protected)

保護成員變量或函數與私有成員十分相似,但有一點不同,保護成員在派生類(即子類)中是可訪問的

#include <iostream>using namespace std ;class Box { public :void SetLenth(int len);int GetLenth(void); private:int Width ;int Height ; protected:int Lenth ; };class SmallBox:Box // SmallBox 是派生類 { public :void SetSmallLenth(int len);int GetSmallLenth(void); };// 子類的成員函數 可以 直接訪問父類的受保護變量 int SmallBox::GetSmallLenth(void) {return Lenth ; }void SmallBox::SetSmallLenth(int len) {Lenth = len ; }void main() {SmallBox box ;box.SetSmallLenth(5); cout << "Lenth is " << box.GetSmallLenth() << endl ; }

?

總結

以上是生活随笔為你收集整理的C++——类访问修饰符的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。