作为指针传递的函数内部的赋值? [英] Assignment inside function that is passed as pointer?

查看:102
本文介绍了作为指针传递的函数内部的赋值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ClassA* pa = NULL;
ClassA* pb = NULL;
assignObject(ClassA* pa,ClassB* pb)
{
pa = new ClassA;
pb = new ClassB;
}

执行函数后,pa,pb的值是什么

what will be the value of pa,pb after executing the function

编辑 如果pa,pb为NULL,则如何通过指针传递返回值

EDIT how to pass as pointer is the return if pa,pb is NULL

推荐答案

如其他答案中所指出-调用后,两者仍然为NULL.但是,有两种可能的解决方案:

As pointed out in other answers - both will still be NULL after the call. However, there are two possible solutions to this problem:

1)引用

void assignObject(ClassA*& pa, ClassB*& pb)
{
    pa = new ClassA;
    pb = new ClassB;
}

ClassA* pa = NULL;
ClassA* pb = NULL;
assignObject(pa, pb); // both will be assigned as expected.

2)指针

void assignObject(ClassA** pa, ClassB** pb)
{
    assert(pa != NULL); assert(pb != NULL);
    *pa = new ClassA;
    *pb = new ClassB;
}
ClassA* pa = NULL;
ClassA* pb = NULL;
assignObject(&pa, &pb); // both will be assigned as expected.

大多数程序员可能会选择引用,因为这样他们就无需声明任何内容(引用永远不能为NULL).

Most programmers would probably choose references because then they don't need to assert anything (references can never be NULL).

这篇关于作为指针传递的函数内部的赋值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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