当函数返回值为引用时,若返回栈变量,不能成为其他引用的初始值,不能作为左值使用
若返回静态变量或全局变量,可以成为其他引用的初始值,即可作为右值使用,也可作为左值使用
//若返回静态变量或全局变量
//可以成为其他引用的初始值
//即可做右值,也可作为左值使用
#include<iostream>
using namespace std;
int getA()
{
int a;
a = 10;
return a;
}
int& getA1()
{
int a;
a = 10;
return a;
}
int getA4()
{
int static b = 10; //static的作用周期为整个程序的执行周期
b++;
return b;
}
int& getA3()
{
int static b = 20;
b++;
return b;
}
int main()
{
int a = getA();
int a1 = getA1();
int &a2 = getA1();
cout <<"a=" <<a<< endl; //输出为10
cout << "a1=" << a1 << endl; //输出为10
cout << "a2=" << a2 << endl; //输出为乱码
int b = 0;
int b1 = 0;
b = getA4();
b1 = getA3();
int &b2 = getA3();
cout << "b=" << b << endl; //输出为11
cout << "b1=" << b1 << endl; //输出为21
printf("b2=%d", b2); //输出为22
system("pause");
}
/函数返回值为引用,可以做左值
#include<iostream>
using namespace std;
//返回的仅仅是一个值
int myget1()
{
static int a=90;
a++;
return a;
}
//返回的是一个变量
int& myget2()
{
static int b=40;
b++;
cout <<"b="<< b<< endl;
return b;
}
int main()
{
int c = 20;
int b;
int d;
d = myget1();
cout << "d="<<d<< endl;
myget2() = 20; //函数返回值是引用,并且可以做左值
b = myget2(); //函数返回值是引用,并且可以做右值
cout << "b="<<b<< endl;
//cout << "myget2()="<<myget2()<< endl;
system("pause");
}