看板 C_and_CPP 關於我們 聯絡資訊
開發平台(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
annheilong: baud 上一行就寫 public 了... 12/01 10:08
nh60211as: 他的base class是public餒 12/01 10:09
loveme00835: 「private只能被自己的member使用,外部無法直接存取 12/01 10:24
loveme00835: 」這個描述就是錯的. 做 access control 其一是為了 12/01 10:24
loveme00835: information hiding, 讓使用者不要過分依賴實作, 而 12/01 10:24
loveme00835: 導致修改擴散到很多地方; 其二是為了確保 invariant. 12/01 10:24
loveme00835: 如果管理得很好, 那用 public 還是 private 除了會 12/01 10:24
loveme00835: 影響 object layout 以外基本沒什麼差別, 像 local c 12/01 10:24
loveme00835: lass 全部都 public 或把耦合已經夠高的類別/函式變 12/01 10:24
loveme00835: 成 friend 都是常有的事 12/01 10:24
sstrange: 我看來被文件誤導了,文件上是把baud放在private上的 12/01 11:18
milkdragon: baud 在 SerialBase 雖是 public,但因 UnbufferedSer 12/02 20:02
milkdragon: ial private 繼承 SerialBase,故文件把 baud 放在 12/02 20:02
milkdragon: private。 然而 UnbufferedSerial 在 public 部分加了 12/02 20:02
milkdragon: 一行 using SerialBase::baud; 使 baud 恢復了 public 12/02 20:02
milkdragon: 的身份 12/02 20:02