您的位置:程序门 -> c/c++ -> c++ 语言



关于传引用


[收藏此页] [打印本页]选择字色:背景色:字体:[][][]


关于传引用
发表于:2008-01-10 22:56:06 楼主
下面这个函数明明是传的引用,为什么值为改变?
#include <iostream>
#include"emp.h"
#include"linked.h"
using   namespace   std;
typedef   employee*   empptr;
void   sample   (empptr   xptr,   empptr   yptr)
{
        xptr   =   yptr;
}   //   sample

int   main()
{
empptr   emp1ptr,
              emp2ptr;
emp1ptr   =   new   employee;
emp2ptr   =   new   employee;
(*emp1ptr).readinto();
(*emp2ptr).readinto();
sample   (emp1ptr,   emp2ptr);
  (*emp1ptr).printout();
  (*emp2ptr).printout();
          cin.get();
          cin.get();
        return   0;
}
我觉得emp1ptr和emp2ptr在传到sample后都指向emp1ptr.至少在c#和java里是这样的。
发表于:2008-01-10 23:01:251楼 得分:0
怎么会改变呢?呵呵
你写的不就是
void   fun(char   *a,   char   *b)
{
        a   =   b;
}
这个函数能实现任何功能吗?

你用的是指针
不是引用!
发表于:2008-01-10 23:03:332楼 得分:0
void       sample       (empptr&       xptr,     empptr     yptr)  
{  
                xptr       =       yptr;  
}       //       sample  

这才是传引用,你那个是传指针;执行完毕后指针的值不会改变。
发表于:2008-01-10 23:09:083楼 得分:0
void       sample       (empptr       xptr,       empptr       yptr)  
{  
                *xptr       =       *yptr;  
}      
发表于:2008-01-10 23:31:464楼 得分:0
执行完后不是xptr指向yptr吗,然后实参emp1ptr会指向emp2ptr吗?
发表于:2008-01-10 23:41:385楼 得分:0
形参xptr指向了yptr,但实参emp1ptr不会变化,不会指向emp2ptr。
这是基本概念,lz最好先写几个1楼那样简单的小程序试一试,彻底弄清楚再研究复杂的程序。
发表于:2008-01-10 23:42:016楼 得分:0
c/c++ code
指针按值传递

发表于:2008-01-10 23:59:337楼 得分:0
再问个问题,为什么下面运算符重载返回的是引用,其实可以没有返回值的   ,这样做有什么好处?
linked <t> &   operator=   (const   linked <t> &   otherlinked)                
                {
                        linked <t>   templinked;

                        node*   tempptr;

                        //   destroy   the   calling   object:
                        while   (head   !=   null)
                                pop_front();

                        //   copy   otherlinked   to   templinked,   in   reverse   order.
                        for   (tempptr   =   otherlinked.head;   tempptr   !=   null;
                                                                                          tempptr   =   tempptr   ->   next)
                                templinked.push_front   (tempptr   ->   item);

                        //   copy   templinked   to   linked   container,   in   reverse   order.
                        //   so   linked   container   has   copy   of   otherlinked   in   order.
                        for   (tempptr   =   templinked.head;   tempptr   !=   null;  
                                                                                        tempptr   =   tempptr   ->   next)
                                push_front   (tempptr   ->   item);

                        return   *this;
                }   //   overloading   =
发表于:2008-01-11 00:49:548楼 得分:0
我觉得   这样做可以   连续赋值  
并且由返回引用   没有产生临时对象   效率也提高了


快速检索

最新资讯
热门点击