C++文件流,指針

1、簡單文件輸出流

ofstream outFile;
outFile.open("filetest.txt");
outFile << "這是文本輸出流的測試文件" << endl;
outFile.close();9

2、文本輸入測試

ifstream infile("filetest.txt");
if (infile.is_open()==false){   
    cout << "不能打開 " << endl;
}
else
{
    char buffer[50];
    infile.getline(buffer, 50);
    cout << buffer << endl;
}

3、函數原型中可以不含變量名

void cheers (int );

4、形參傳遞中數組名和實際和指針代表的含義相同.使用sizeof 打印傳遞的數組的長度,實際上智能顯示指針的長度,因爲實際算上傳遞的就是指針。

int sum_arr(int arr[], int n) ;
int sum_arr(int *arr,  int n);

5、

void show_array(const double arr[], int n);

意味着 其中在本函數中 ,通過 arr[]指向的那個數組,通過使用arr[x]的方式不能修改其值

6、const 與指針

  • const 變量地址 –>const指針 合法
  • const 變量地址 –>普通指針 非法
  • 非const變量指針–>const指針 合法
  • const變量地址 –>const指針 合法
int age =39;
const int * pt=&age;

const float g_earth =9.80;
const float *pe =&g_earth;

const float g_moon 1.163;
float *p =&g_moon;
  • 哪個參數是const 的注意看const後面是什麼,是指針還是解引用
int * const finger =&sloth;       //const 後面是指針finger 故指針不能變化,指向的內容可以變
int const * finger =&sloth;       //const 後面的是* finger 故解引用不可變,指針可以變化
const int * const finger &sloth; //兩個const 故指針和解引用均不可變

image

7、指針數組與數組指針

  • 通過結合性分析,若沒有括號,則應該爲右結合性,說明是個數組;若有括號,則括號內先結合,應該是個指針
int  * arr[4];     //指針數組,存儲4int* 的數組
int  (*arr)[4]     //數組指針,指針指向一個形如 int a[4] 的數組

8、函數指針,返回函數的指針

double pam (int );
double (*pf)(int);

pf=pam;

pam(5);
(*pf)(5);     //以上兩種都是調用pam 函數,功能相同。
  • 以下幾項等價
double *f1 (const double ar[], int n);
double *f2 (const double []  , int n);
double *f3 (const double *   ,int n);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章