C ++通过引用传递指针并分配默认值 [英] C++ pass pointer by reference and assign default value

查看:98
本文介绍了C ++通过引用传递指针并分配默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过对函数的引用来传递指针,这样我实际上可以更改传递的指针所指向的地址,并且我想为该参数分配一个默认值.

I would like to pass a pointer by reference to a function, such that i can actually change the address the passed pointer is pointing to and i'd like to assign this argument a default value.

类似这样的东西:

在声明中

void myFunc(SomeType* &var=NULL);

和定义:

void MyClass::myFunc(SomeType* &var){
    if(var!=NULL)
        (*var)=(*someOtherPointer);

    if(someCondition)
        var=NULL;
}

,以便被调用者可以决定是要使用一个参数还是不使用参数来调用该函数.这样,如果他决定传递一个参数,并且someCondition成立,则传递的指针之后将指向NULL

such that a callee can decide whether he wants to call the function with one argument or without argument. And sucht that if he decides to pass an argument, and someCondition holds, the passed pointer will point to NULL afterwards

但是-如果我尝试这样做,我会得到:

however - if i try to do it like this i get a:

错误C2440:默认参数":"int"不能被迷惑为"SomeType *&"

Error C2440: 'default argument': 'int' cannot be conveted to 'SomeType *&'

感谢您的帮助!

推荐答案

错误消息说明了这一切:您正在传递一个整数,而不是一个指向Pointer-to-SomeType的引用.要执行您想要的操作,可以使用指向SomeType的指针:

The error message says it all: you are passing an integer instead of a reference-to-a-pointer-to-SomeType. To do what you want, you can use a pointer-to-a-pointer-to-SomeType:

void myFunc(SomeType** var=NULL);

void MyClass::myFunc(SomeType** var){
    if(var!=NULL && *var!=NULL)
        (**var)=(*someOtherPointer);

    if(var!=NULL && someCondition)
        *var=NULL;
}

这篇关于C ++通过引用传递指针并分配默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆