void doubleValue(int *val)
{
*val *= 2;
}
这个函数的目的是使 val 指向的变量翻倍。当 val 被解引用时,*= 运算符对 val 指向的变量起作用。该语句可以将地址存储在 val 中的原始变量乘以 2。当然,当调用该函数时,必须使用被翻倍的变量地址作为实参,而不是变量本身作为实参。doubleValue(&number);
该语句使用了地址运算符(&)将 number 的地址传递到 val 形参中。函数执行后,number 的内容将被乘以 2。下面的程序演示了该函数的用法:
//This program uses two functions that accept addresses of variables as arguments.
#include <iostream>
using namespace std;
//Function prototypes
void getNumber(int *);
void doubleValue(int *);
int main()
{
int number;
//Call getNumber and pass the address of number
getNumber(&number);
// Call doubleValue and pass the address of number
doubleValue(&number);
// Display the value in number
cout << "That value doubled is " << number << endl;
return 0;
}
void getNumber(int *input)
{
cout << "Enter an integer number: ";
cin >> *input;
}
void doubleValue(int *val)
{
*val *= 2;
}
程序输出结果:
Enter an integer number: 10
That value doubled is 20
void getNumber(int *);
void doubleValue(int *);
cin >> *input;
间接运算符会使用户输入的值存储在 input 指向的变量中,而不是 input 中。
//This program demonstrates that a pointer may be used as a parameter to accept the address of an array. Either subscript or pointer notation may be used.
#include <iostream>
#include <iomanip>
using namespace std;
// Function prototypes
void getSales(double *sales, int size);
double totalSales(double *sales, int size);
int main()
{
const int QUARTERS = 4;
double sales[QUARTERS];
getSales(sales, QUARTERS);
cout << setprecision(2);
cout << fixed << showpoint;
cout << "The total sales for the year are $";
cout << totalSales(sales, QUARTERS) << endl;
return 0;
}
void getSales(double *array, int size)
{
for (int count = 0; count < size; count++)
{
cout << "Enter the sales figure for quarter ";
cout << (count + 1) << ": ";
cin >> array[count];
}
}
double totalSales(double *array, int size)
{
double sum = 0.0;
for (int count = 0; count < size; count++)
{
sum += *array;
array++;
}
return sum;
}
程序输出结果:
Enter the sales figure for quarter 1: 10263.98
Enter the sales figure for quarter 2: 12369.69
Enter the sales figure for quarter 3: 11542.13
Enter the sales figure for quarter 4: 14792.06
The total sales for the year are $48967.86
cin >> array[count];
在 totalSales 函数中,array 还可以与以下语句中的间接运算符一起使用:sum += *array;
而在接下来的语句中,array 中的地址则可以递增,以使指向下一个元素:array++;
上面介绍的两个语句也可以合并成以下语句:sum += *array++;
* 运算符将首先解引用 array,然后++ 运算符将使得 array 中的地址递增。
版权说明:Copyright © 广州松河信息科技有限公司 2005-2025 版权所有 粤ICP备16019765号
广州松河信息科技有限公司 版权所有