從Hello world開始
hello world.cpp
#include <iostream>
using namespace std;
int main(){
cout<<"Hello world"<<endl;
}
include <iostream>
:表示的含義是IO
流頭文件;
using namespace std;
:表示的含義是命名空間;
cout
, cin
表示的是命名空間里面的輸出,輸入對象,<<
:表示的是輸出運算符,>>
:表示的是輸入運算符號;
關于文件后綴
C語言的后綴通常是*.c
,但是C++的后綴名通常是*.cpp
、*.cc
、*.cxx
但是在Linux底下通常建議使用*.cpp
;
頭文件的區別
C++頭文件使用C標準庫,通常是在C標準庫的文件名前面加上c
,但是需要省略.h
;例如<cstdlib>
、<cstring>
;
函數重載
函數重載表示的是在函數名相同,且只有參數(個數或者類型)不相同時;C
語言是不支持重載的,但是C++是支持重載的;
關于重載的兩個示例
printf.c
#include <stdio.h>
void printf(){
printf("Hello world");
}
int main(){
printf();
}
運行這個代碼會出現: error: conflicting types for ‘printf’
也就是出現類型沖突;
*printf.cpp
#include <cstdio>
void printf(){
printf("Hello world");
}
int main(){
printf();
}
在這個過程中會出現函數重載的情況,printf(),
因為沒有參數會執行定義的函數printf(),如果有參數就會執行系統函數;
命名空間
*test.c
#include <stdio.h>
void test(){
printf("this is test\n");
}
void test(){
printf("this is another test\n");
}
int main(){
test();
}
會出現:error: redefinition of ‘test’;也就是出現函數名的重聲明;
這個重聲明的錯誤可以在C++
中使用命名空間來解決;
- 定義命名空間
namespace 空間名 {
}
- 引用命名空間
using namespace 空間名;
- 標準命名空間
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;
}
*面向過程:強調的是如何處理;
*面向對象:強調的是執行處理的對象;
動態內存
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來申請和釋放內存;
dynamic_mem.cpp
#include <iostream>
int main(){
int* num = new int;
*num = 100;
std::cout << *num << std::endl;
delete num;
}
*C++使用的是new和delete來申請和釋放內存,并且不建議這兩個函數進行混用;
*malloc 和free 雖然可以使用new和delete混合使用的,但是編譯器處理的情況不同,所以是不建議混合使用的,并且new,delete做的操作要比malloc和free更多;所以需要注意的是malloc申請的內存,使用free釋放時,需要將這個指針指為NULL;