struct在C和C++中的使用總結

來源:互聯網
上載者:User

標籤:舉例   bubuko   ace   sys   基本   fine   實現   clu   nbsp   

主要理解一下兩點:

1.在C和C++中struct的常規使用。

2.在C++中struct和class基本一致,除了在存取控制許可權方面,即:

    通過struct關鍵字實現的類,屬性,函數預設的存取權限為public;
    通過class關鍵字實現的類,屬性,函數預設的存取權限為private。

下面舉例說明:

#include<iostream>using namespace std;struct point{int x;int y;int fun(point &p)//在C++中,完全可以在struct中使用函數{p.x = 100;p.y = 200;return 0;}point(int x, int y): x(x) , y(y){ }//等同於C++中的class};struct teacher{int age;char *name;};int main(void){point p(0,0);p.x = 1;p.y = 2;point p1= p;cout<<"p1.x="<<p1.x<<endl;cout<<"p1.y="<<p1.y<<endl;point *p3 = &p1;p3->x = 10;p3->y = 20;cout<<"p3->x="<<p3->x<<endl;cout<<"p3->y="<<p3->y<<endl;p3->fun(p1);cout<<"p3->x="<<p3->x<<endl;cout<<"p3->y="<<p3->y<<endl;point p4(1000,2000);cout<<"p4.x="<<p4.x<<endl;cout<<"p4.y="<<p4.y<<endl;cout<<"================struct在C中用法================"<<endl;cout<<"before define struct teacher,sizeof(teacher)="<<sizeof(teacher)<<endl;struct teacher t1;//定義時比較繁瑣,需要添加struct關鍵字,也可以使用typedef聲明,此處就不需要加struct關鍵字。同樣在C++中可以直接不加struct關鍵字cout<<"after define struct teacher,sizeof(teacher)="<<sizeof(teacher)<<endl;t1.age = 30;t1.name = "zhangsan";cout<<"t1.age="<<t1.age<<endl;cout<<"t1.name="<<t1.name<<endl;struct teacher *t2 = &t1;t2->age = 35;t2->name = "lisi";cout<<"t2->age="<<t2->age<<endl;cout<<"t2->name="<<t2->name<<endl;system("pause");return 0;}

  輸出結果:

 

struct在C和C++中的使用總結

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.