当前位置:编程学习 > C/C++ >>

具有返回值的函数之作为

首先解释一下文章标题,听起来有点拗口,意思是:具有返回值的函数,在调用时以及返回时都做了哪些事情(这些事情往往从代码表面是看不到的)。

一、原理
关于函数的返回值,先说下 return 语句,return 语句结束当前正在执行的函数,并将控制权返回给调用此函数的函数。有两种形式:

1.return; //不带返回值的函数中(void)
不带返回值的 return 语句只能用于返回类型为 void 的函数。但是注意:在返回类型为void的函数中,return 语句也不是必须的,隐式的 return 发生在函数的最后一个语句完成时。

一般情况下,返回类型为 void 的函数使用 return 语句是为了引起函数的强制结束(类似于循环结构中的break语句)。

2.return expression: //带返回值的函数中(非void)
此情况下,返回值的类型必须和函数的返回类型相同,或者能隐式转化为函数的返回类型。

函数的返回值:用于初始化在调用函数出创建的临时对象(temporary object)。

对于具有返回值的函数,在函数调用时(如求解表达式),需要一个地方存储器运算结果,此时编译器会创建一个没有命名的对象-----临时对象。

如:


[cpp] 
... 
int add(int a, int b) 

    return a + b ; 

.... 
int a = 1; 
int b = 2; 
int c = add(a, b); //create temporary, delete it after executing this statement  
... 

...
int add(int a, int b)
{
    return a + b ;
}
....
int a = 1;
int b = 2;
int c = add(a, b); //create temporary, delete it after executing this statement
...
上面的代码中,在 int c = add (a, b);时,发生了如下事情:


首先:创建了一个临时对象,如temp。
然后:将函数的返回值 a+ b 的副本 复制给 temp;
最后:将temp 的副本复制给 变量 c,并删除临时变量 temp

注:在英语中,C++ 程序员通常用temporary 这个术语来代替 temporary object。

二、例子
为了更清晰地看到具有具有返回值函数之作为,下面以一个类的运行情况说明:


[cpp] 
#include <iostream>  
using namespace std; 
class A 

private: 
    int m_x; 
public: 
    A(int x=0):m_x(x){cout<<"constructor, value: "<<m_x<<endl;} 
    A(const A& a) 
    { 
        m_x = a.m_x; 
        cout<<"copy constructor, value: "<<m_x<<endl; 
    } 
    A& operator=(const A& a) 
    { 
        m_x = a.m_x; 
        cout<<"assignment operator, value: "<<m_x<<endl; 
        return *this; 
    } 
    ~A(){cout<<"destructor, value: "<<m_x<<endl;} 
    A getOneObject(int x) 
    { 
        cout<<"in fun call"<<endl; 
        A a(0); 
        a.m_x =x; 
 
        return a; 
    } 
 
}; 
 
int main() 

    A a1(1); 
    A a2(2); 
    cout<<"before fun call"<<endl; 
    a2= a1.getOneObject(3); 
    cout<<"after fun call"<<endl; 
    cout<<"before quit"<<endl; 
    return 0; 

#include <iostream>
using namespace std;
class A
{
private:
 int m_x;
public:
 A(int x=0):m_x(x){cout<<"constructor, value: "<<m_x<<endl;}
 A(const A& a)
 {
  m_x = a.m_x;
  cout<<"copy constructor, value: "<<m_x<<endl;
 }
 A& operator=(const A& a)
 {
  m_x = a.m_x;
  cout<<"assignment operator, value: "<<m_x<<endl;
  return *this;
 }
 ~A(){cout<<"destructor, value: "<<m_x<<endl;}
 A getOneObject(int x)
 {
  cout<<"in fun call"<<endl;
  A a(0);
  a.m_x =x;

  return a;
 }

};

int main()
{
 A a1(1);
 A a2(2);
 cout<<"before fun call"<<endl;
 a2= a1.getOneObject(3);
 cout<<"after fun call"<<endl;
 cout<<"before quit"<<endl;
 return 0;
}
输出结果:

 

\

 

补充:软件开发 , C++ ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,