[問題] private的使用方式

看板C_and_CPP (C/C++)作者 (Q^_________^Q)時間4年前 (2020/12/01 09:58), 編輯推噓1(1015)
留言16則, 5人參與, 4年前最新討論串1/1
開發平台(Platform): (Ex: Win10, Linux, ...) Linux 編譯器(Ex: GCC, clang, VC++...)+目標環境(跟開發平台不同的話需列出) GCC Mbed for ARM Cortex-M4 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) 問題(Question): 最近在學習Mbed OS的開發,看了很多官網的sample code,因為之前都使用C沒使用過C++ 在看到serial的driver時,sample code的main function直接使用private member? 以前的觀念是private只能被自己的member使用,外部無法直接存取 https://os.mbed.com/docs/mbed-os/v6.3/apis/unbufferedserial.html 裡面的sample serial_port.baud(9600); baud是private member卻可以在main裡面直接使用,這樣是正確的嗎? 餵入的資料(Input): 預期的正確結果(Expected Output): 錯誤結果(Wrong Output): 程式碼(Code):(請善用置底文網頁, 記得排版,禁止使用圖檔) class SerialBase : private NonCopyable<SerialBase> { public: void baud(int baudrate); .... } int main(void) { // Set desired properties (9600-8-N-1). serial_port.baud(9600); serial_port.format( /* bits */ 8, /* parity */ SerialBase::None, /* stop bit */ 1 ); // Register a callback to process a Rx (receive) interrupt. serial_port.attach(&on_rx_interrupt, SerialBase::RxIrq); } 補充說明(Supplement): -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 210.201.89.41 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1606787936.A.B95.html

12/01 10:08, 4年前 , 1F
baud 上一行就寫 public 了...
12/01 10:08, 1F

12/01 10:09, 4年前 , 2F
他的base class是public餒
12/01 10:09, 2F

12/01 10:24, 4年前 , 3F
「private只能被自己的member使用,外部無法直接存取
12/01 10:24, 3F

12/01 10:24, 4年前 , 4F
」這個描述就是錯的. 做 access control 其一是為了
12/01 10:24, 4F

12/01 10:24, 4年前 , 5F
information hiding, 讓使用者不要過分依賴實作, 而
12/01 10:24, 5F

12/01 10:24, 4年前 , 6F
導致修改擴散到很多地方; 其二是為了確保 invariant.
12/01 10:24, 6F

12/01 10:24, 4年前 , 7F
如果管理得很好, 那用 public 還是 private 除了會
12/01 10:24, 7F

12/01 10:24, 4年前 , 8F
影響 object layout 以外基本沒什麼差別, 像 local c
12/01 10:24, 8F

12/01 10:24, 4年前 , 9F
lass 全部都 public 或把耦合已經夠高的類別/函式變
12/01 10:24, 9F

12/01 10:24, 4年前 , 10F
成 friend 都是常有的事
12/01 10:24, 10F

12/01 11:18, 4年前 , 11F
我看來被文件誤導了,文件上是把baud放在private上的
12/01 11:18, 11F

12/02 20:02, 4年前 , 12F
baud 在 SerialBase 雖是 public,但因 UnbufferedSer
12/02 20:02, 12F

12/02 20:02, 4年前 , 13F
ial private 繼承 SerialBase,故文件把 baud 放在
12/02 20:02, 13F

12/02 20:02, 4年前 , 14F
private。 然而 UnbufferedSerial 在 public 部分加了
12/02 20:02, 14F

12/02 20:02, 4年前 , 15F
一行 using SerialBase::baud; 使 baud 恢復了 public
12/02 20:02, 15F

12/02 20:02, 4年前 , 16F
的身份
12/02 20:02, 16F
文章代碼(AID): #1VnQDWkL (C_and_CPP)
文章代碼(AID): #1VnQDWkL (C_and_CPP)