C/C++(C++類型增強)

來源:互聯網
上載者:User

標籤:ons   string類   namespace   比較   必須   資料   name   als   pre   

C++類型增強型別檢查更嚴格

把一個const類型的指標賦給非const類型的指標。c語言中可以通的過,但是在c++中則編不過去

const int a = 10;a = 100;//const修飾的不能修改int *p = &a;*p = 100;printf("a = %d\n",a);//a = 100,c裡面類型不嚴密,指標能修改const修飾的變數,實際是a是const int *類型,也就是說強行的賦給int *,把const漏掉了。const int a與int const a一樣,看const修飾誰把類型去掉。int *const p;把int去掉,p不能改變,p指向的內容可以改變。const int *const p;它指向的本身和內容都不能改變。
#include<iostream>using namespace std;int main() {    const int a = 100;//const修飾的必須要初始化    int *p = &a;//不可以報錯 const int *無法轉化成int *;    const int *p = &a;//才是正確的    //C++不需要強轉    char *p = malloc(100);//C++會報錯    char *q = (char*)malloc(100);//void *    return 0;}
布爾類型(bool)

c 語言的邏輯真假用 0 和非 0 來表示。而 c++中有了具體的類型。

int main(){    bool flag = true;    if(flag)        printf("hello world!\n");    else        printf("hello C++!\n");    return 0;}
真正的枚舉(enum)

c 語言中枚舉本質就是整型,枚舉變數可以用任意整型賦值。而 c++中枚舉變數,只能用被枚舉出來的元素初始化。

bool用枚舉實現過程:

#include<iostream>enum BOOL{    FALSE,TURE};int main(){    const int a = 100;    BOOL flag = TRUE;    bool aa = true;    if(flag)        cout<<a;        printf("sizeof(flag) = %d sizeof(BOOL) = %d sizeof(bool) = %d\n",sizeof(flag),sizeof(BOOL),sizeof(bool));}//sizeof(flag) = 4 sizeof(BOOL) = 4 sizeof(bool) = 1//enum枚舉本質是整型

它和即將所學的string類型並不是實際意義上的資料類型而是一個對象。

enum SEASOM{    Spr,Sum,Autu,Win};int main(){    SEASON s;    s = Win;//在C++中比較嚴格,除了枚舉外的無法賦值。c裡面就可以賦其他值。    return 0;}

其實枚舉可以和宏來等價

#define Spr 0#define Sun 1....enum{    Spr = 1,Sum,Autu,Win};

在C++中經可能的使用枚舉,const代替使用宏。

運算式的值可被賦值

c:

int main(){    int a,b=10;    a = b = 100;//100賦值給b,b = 100這個運算式賦值給a。    (a = b) = 100;//錯誤,運算式是不可被賦值的    (a != b?a:b) = 1000;//錯誤    return 0;}

c++

int main(){    int a,b = 5;    (a = b) = 100;    printf("a = %d b = %d\n",a,b);    (a != b?a:b) = 1000;    printf("a = %d b = %d\n",a,b);    return 0;}//a = 100,b = 5;//a = 1000,b = 5//a = b是一個運算式,b的值賦值給a,最後把100的值賦值給a,b的值沒發生變化。

體現C++對C語言的限制與提升

cin cout類對象

scanf printf函數的功能相同

int main(){    char name[30];    scanf("%s",name);//不安全的輸入,輸入很多會掛機    fgets(name,30,stdin);//最多隻能輸入29個字元,比較安全。    cin>>name;//>>流輸入運算子    cout<<"name = "<<name<<endl;//"name = "字串流入cout對象,name流入cout對象,endl(換行)流入cout對象中,從左至右的順序。    string name1;    cin>>name1;    cout<<name1;    //很安全,輸多少都不會掛機    cin>>a>>b;//有順序,從鍵盤輸入的第一個數流入a,第二個數流入b    //<=>    cin>>a;    cin>>b;    return 0;}

C/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.