Day1-C++初識

從Hello world開始

hello world.cpp

#include <iostream>
using namespace std;
int main(){
    cout<<"Hello world"<<endl; 
}

include <iostream>:表示的含義是IO流頭文件;
using namespace std;:表示的含義是命名空間;
cout, cin表示的是命名空間里面的輸出,輸入對象,<<:表示的是輸出運(yùn)算符,>>:表示的是輸入運(yùn)算符號;

關(guān)于文件后綴

C語言的后綴通常是*.c,但是C++的后綴名通常是*.cpp*.cc*.cxx但是在Linux底下通常建議使用*.cpp

頭文件的區(qū)別

C++頭文件使用C標(biāo)準(zhǔn)庫,通常是在C標(biāo)準(zhǔn)庫的文件名前面加上c,但是需要省略.h;例如<cstdlib><cstring>

函數(shù)重載

函數(shù)重載表示的是在函數(shù)名相同,且只有參數(shù)(個數(shù)或者類型)不相同時;C語言是不支持重載的,但是C++是支持重載的;
關(guān)于重載的兩個示例

  • printf.c
#include <stdio.h>
void printf(){
    printf("Hello world");
}
int main(){
    printf();
}
運(yùn)行這個代碼會出現(xiàn): error: conflicting types for ‘printf’
也就是出現(xiàn)類型沖突;

*printf.cpp

#include <cstdio>
void printf(){
    printf("Hello world");
}
int main(){
    printf();
}
在這個過程中會出現(xiàn)函數(shù)重載的情況,printf(),
因?yàn)闆]有參數(shù)會執(zhí)行定義的函數(shù)printf(),如果有參數(shù)就會執(zhí)行系統(tǒng)函數(shù);

命名空間

*test.c

#include <stdio.h>
void test(){
    printf("this is test\n");
}
void test(){
    printf("this is another test\n");
}
int main(){
    test();
}
會出現(xiàn):error: redefinition of ‘test’;也就是出現(xiàn)函數(shù)名的重聲明;

這個重聲明的錯誤可以在C++中使用命名空間來解決;

  • 定義命名空間
namespace 空間名 {
}
  • 引用命名空間
using namespace 空間名;
  • 標(biāo)準(zhǔn)命名空間std
using namespace std;

C++命名空間處理方式

#include <cstdio>
namespace scope1 {
    void test(){
        printf("this is test\n");
    }
}
namespace scope2 {
    void test(){
        printf("this is another test\n");
    }
}
int main(){
    scope1::test();
    scope2::test();
}

類型

*新增的類型是bool true/false

  • password.cpp
#include <iostream>
#include <cstdio>
using namespace std;
int main(){
      cout << "input user name:";
      char name[BUFSIZ];
      cin >> name;
      cout << "input 3 number password:";
      int password1;
      cin >> password1;
      cout << "input 3 number password again:";
      int password2;
      cin >> password2;
      cout << "password check:" << (password1 == password2) << endl;
}

*面向過程:強(qiáng)調(diào)的是如何處理;
*面向?qū)ο螅簭?qiáng)調(diào)的是執(zhí)行處理的對象;

動態(tài)內(nèi)存

  • dynamic_mem.c
#include <stdio.h>
#include <stdlib.h>
int main(){
      int* num = malloc(sizeof(int));
      *num = 100;
      printf("%d\n",*num);
      free(num); 
}
*C語言使用的是malloc和free來申請和釋放內(nèi)存;
  • dynamic_mem.cpp
#include <iostream>
int main(){
      int* num = new int;
      *num = 100;
      std::cout << *num << std::endl;
      delete num; 
}
*C++使用的是new和delete來申請和釋放內(nèi)存,并且不建議這兩個函數(shù)進(jìn)行混用;

*malloc 和free 雖然可以使用new和delete混合使用的,但是編譯器處理的情況不同,所以是不建議混合使用的,并且new,delete做的操作要比malloc和free更多;所以需要注意的是malloc申請的內(nèi)存,使用free釋放時,需要將這個指針指為NULL;

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容