在結構體或類中, 指針訪問其成員函數或變量通過 "->" 運算符或者看代碼注釋部分, 注釋部分的操作不推薦:
#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++結構體與類指針全部知識點內容,感謝大家的閱讀和對武林網的支持。
新聞熱點
疑難解答
圖片精選