函数名前的 ‘&’ 可以让你用 &函数名()
的方式获取返回值的地址。这种方法可不等同于新创建一个变量,用这个变量接收返回值,然后再用 &变量
的方式获取地址(我们都知道新创建的变量的内存地址是重新开辟的内存,和函数的返回值地址没有任何关系)。
// Test_Console.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include <Windows.h>
#include <iomanip>
#include <fstream>
#include<cstdlib>
#include<string>
using namespace std;
int a = 123456;
int func1(){
return a;
}
int& func2(){
return a;
}
int _tmain(int argc, _TCHAR* argv[])
{
cout << "&a:" << &a << endl;
cout << "func1():" << func1() << endl;
//cout << "&func1():" << &func1() << endl; // 语法错误
cout << "func2():" << func2() << endl;
cout << "&func2():" << &func2() << endl;
getchar();
return 0;
}
效果图: