第十二課:指針強化
學(xué)習(xí)目標(biāo):
- 理解常量指針與指針常量的區(qū)別。
- 學(xué)習(xí)如何使用函數(shù)指針。
- 掌握指針與數(shù)組的高級使用技巧。
學(xué)習(xí)內(nèi)容:
-
常量指針與指針常量
- 概念: 常量指針是一個指向常量的指針,這意味著不能通過這個指針來修改其指向的值。指針常量是一個指針,其自身的值不可以修改,但它可以修改其指向的內(nèi)容。
-
代碼示例:
#include <iostream> int main() { int value = 10; int anotherValue = 20; // 常量指針 const int *ptr = &value; // ptr = &anotherValue; // 正確,可以改變指針指向 // *ptr = 15; // 錯誤,不能通過ptr改變value的值 // 指針常量 int *const ptrConst = &value; *ptrConst = 15; // 正確,可以改變value的值 // ptrConst = &anotherValue; // 錯誤,不能改變指針的指向 std::cout << "Value through constant pointer: " << *ptr << std::endl; std::cout << "Value through pointer constant: " << *ptrConst << std::endl; return 0; }
-
預(yù)計輸出效果:
Value through constant pointer: 10 Value through pointer constant: 15
- 使用場景: 當(dāng)你想保護(hù)指針指向的數(shù)據(jù)不被修改時使用常量指針,當(dāng)你不想改變指針的指向時使用指針常量。
-
函數(shù)指針
- 概念: 函數(shù)指針是指向函數(shù)的指針,通過這個指針可以調(diào)用不同的函數(shù)。
-
代碼示例:
#include <iostream> void greetEnglish() { std::cout << "Hello!" << std::endl; } void greetSpanish() { std::cout << "?Hola!" << std::endl; } int main() { // 函數(shù)指針 void (*greet)() = nullptr; greet = &greetEnglish; // 指向greetEnglish函數(shù) greet(); // 調(diào)用greetEnglish greet = &greetSpanish; // 指向greetSpanish函數(shù) greet(); // 調(diào)用greetSpanish return 0; }
-
預(yù)計輸出效果:
Hello! ?Hola!
- 使用場景: 當(dāng)你需要在運行時調(diào)用不同的函數(shù)時,函數(shù)指針特別有用,例如回調(diào)函數(shù)或事件處理。
-
指針與數(shù)組的高級應(yīng)用
- 概念: 指針可以用來遍歷數(shù)組,通過指針偏移量來訪問數(shù)組元素。
-
代碼示例:
#include <iostream> int main() { int numbers[] = {10, 20, 30, 40, 50}; int *ptr = numbers; // 指向數(shù)組第一個元素 for (int i = 0; i < 5; ++i) { std::cout << "Number[" << i << "] = " << *(ptr + i) << std::endl; } return 0; }
-
預(yù)計輸出效果:
Number[0] = 10 Number[1] = 20 Number[2] = 30 Number[3] = 40 Number[4] = 50
- 使用場景: 當(dāng)需要遍歷數(shù)組或動態(tài)分配的數(shù)組時,指針提供了一種靈活的訪問和操作數(shù)組元素的方式。
練習(xí)題: 編寫一個C++程序,創(chuàng)建一個包含5個整數(shù)的數(shù)組。使用函數(shù)指針指向一個函數(shù),該函數(shù)將數(shù)組作為參數(shù),并返回數(shù)組中的最大值。在main
函數(shù)中調(diào)用這個函數(shù),并輸出結(jié)果。
答案:
#include <iostream>
// 函數(shù)原型聲明
int getMax(int*, int);
int main() {
int arr[] = {3, 1, 4, 1, 5};
int arraySize = sizeof(arr) / sizeof(arr[0]);
// 函數(shù)指針聲明
int (*funcPtr)(int*, int) = nullptr;
funcPtr = &getMax; // 指向getMax函數(shù)
// 通過函數(shù)指針調(diào)用getMax
int max = funcPtr(arr, arraySize);
std::cout << "The maximum value in the array is: " << max << std::endl;
return 0;
}
// 定義getMax函數(shù)
int getMax(int* array, int size) {
int max = array[0];
for (int i = 1; i < size; ++i) {
if (array[i] > max) {
max = array[i];
}
}
return max;
}
預(yù)計輸出效果:文章來源:http://www.zghlxwxcb.cn/news/detail-814131.html
The maximum value in the array is: 5
目錄
第十三課:結(jié)構(gòu)體和聯(lián)合體文章來源地址http://www.zghlxwxcb.cn/news/detail-814131.html
到了這里,關(guān)于從0開始學(xué)習(xí)C++ 第十二課:指針強化的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!