c++中的指针和自递增参数

Pointers and self incrementing arguments in c++

本文关键字:参数 指针 c++      更新时间:2023-10-16

请记住,我是指针的新手。

我试图实现的是,每次迭代for循环时,value都会增加一个双倍的值(在本例中为.013):

/***********************************************************************************
@name:      fill_array
@purpose:   fill all elements in range 'begin' to 'end' with 'value'
@param:     double* begin   address of first element of the array range
@param:     double* end     address of the next byte past the end of the array range
@param:     double  value   the value to store in each element
@return:    void
***********************************************************************************/
void fill_array(double* begin, double* end, double value) {
    for( ; begin < end; begin++)
        *begin = value == 0.0 ? 0.0 : value;
}

一个不起作用的驱动程序代码示例(我提供这个只是为了更好地传达我想要实现的目标):

double dataValue = 3.54;
double* currentData = &dataValue;
fill_array(begin, end, *currentData+.013);

当然,存储在数组中的所有值都是3.553。

我是否需要创建一个带有返回值的函数,作为参数传递到形式参数"value"中?或者这可以只用指针来完成吗?

只需在每次迭代中增加值:

for( ; begin < end; begin++) {
    *begin = value == 0.0 ? 0.0 : value;
    value += 0.013;
}

如果您不希望0.013是一个动态的,那么您应该在函数中添加另一个参数(例如double incrementer)。

每次遍历for循环时,值都会增加一个双倍值(在本例中为.013):

value是调用者提供的函数参数,所以调用者可以这样修改:

fill_array(begin, end, *currentData += .013);

如果您不希望调用代码修改值,那么您必须进行一些其他更改,因为给定。。。

fill_array(begin, end, *currentData+.013);

value参数提供了添加的临时结果,并且没有fill_array可以要求控制的非临时变量,以便它可以添加到其中并查看对下一次调用的影响。这可以通过几种方法来解决,使用指针。。。

void fill_array(double* begin, double* end, double* p_value) {
    for( ; begin < end; begin++)
        *begin = *p_value;
    *p_value += 0.13;
}
fill_array(begin, end, currentData);

或使用引用。。。

void fill_array(double* begin, double* end, double& value) {
    for( ; begin < end; begin++)
        *begin = value;
    value += 0.13;
}
fill_array(begin, end, *currentData);

不能使用函数fill_array来完成任务。但是你可以专门为这项任务超载。例如

void fill_array( double *begin, double *end, double init, double incr ) 
{
    init = init == 0.0 ? 0.0 : init;
    if ( begin != end ) 
    {
        *begin = init;
        while ( ++begin != end ) *begin = init += incr;
    }
}

或者,如果您将最后一个参数定义为具有默认参数,则您甚至只能拥有一个函数。例如

void fill_array( double *begin, double *end, double init, double incr = 0.0 ) 
{
    init = init == 0.0 ? 0.0 : init;
    if ( begin != end ) 
    {
        *begin = init;
        while ( ++begin != end ) *begin = init += incr;
    }
}

因此,如果你把它称为

fill_array( begin, end, 3.54 );

它将按照您原来的功能运行。

如果你称之为

fill_array( begin, end, 3.54, 0.13 );

它会表现出你想要达到的效果。