今天在做一個練習時突然被char str[]和char* str給迷住了,研究了半天才搞定
在c++中對char類型做了特殊處理,原因是兼容c語言
eg:
char str[]="abc\0def";
這里的str是一個地址,c++在運行時會自動將str的地址從str[0]一直移動到“\0”;然后輸出結果。\\abd\0
char* str這個是一個野指針,千萬別這樣使用,在類中除外。
小練習
#include <iostream>
using namespace std;

class Book{
private:
char* str;
public:
Book(char str[]);
void show();
};
Book::Book(char str[]){
this->str=str;
};
void Book::show(){
cout<<this->str<<endl;
}

int main(){
Book b("abc\0def");
b->show();
}最后一行寫錯了,應當是b.show();
在c++中對char類型做了特殊處理,原因是兼容c語言
eg:
char str[]="abc\0def";
這里的str是一個地址,c++在運行時會自動將str的地址從str[0]一直移動到“\0”;然后輸出結果。\\abd\0
char* str這個是一個野指針,千萬別這樣使用,在類中除外。
小練習
#include <iostream>
using namespace std;
class Book{
private:
char* str;
public:
Book(char str[]);
void show();
};
Book::Book(char str[]){
this->str=str;
};
void Book::show(){
cout<<this->str<<endl;
}
int main(){
Book b("abc\0def");
b->show();
}



如果你自己嘗試實現以下strcpy之類的C字符串API你更加深刻理解了