在本篇文章裏小編給大家整理了關於C++結構體與類指針知識點以及相關內容,有興趣的朋友們參考學習下。
在結構體或類中, 指針訪問其成員函數或變量通過 "->" 運算符或者看代碼註釋部分, 註釋部分的操作不推薦:
#include <iostream> #include <cstring> using namespace std; struct STRUCT { string hello; }; int main() { STRUCT *str=new STRUCT; str->hello="Hello";//或者可以寫成: (*str).hello="Hello" cout<<str->hello<<endl;//或者可以寫成: cout<<(*str).hello<<endl; delete str; return 0; }
#include <iostream> #include <cstring> using namespace std; class CLASS { public: string hello; }; int main() { CLASS *str=new CLASS; str->hello="Hello";//同理 cout<<str->hello<<endl;//同理 delete str; return 0; }
備註: class中的public不可以省, struct中public可以省 ( 屬於語法部分, 不做解釋 )
關於類與結構體的指針都是這樣操作 (無論是哪種數據類型),
注意: 一定要給結構體或類指針聲明空間, 否則輸出可能會是亂碼或沒有輸出, 本人更建議使用智能指針, 免得申請釋放空間
以上就是本次介紹的關於C++結構體與類指針全部知識點內容,感謝大家的閱讀和對神馬文庫的支持。