在C和C++中,我们可以在表达式的左侧使用函数吗?


在C语言中,我们不能在表达式的左侧使用函数名。在C++中,我们可以这样做。这可以通过一些返回引用变量的函数来实现。

C++函数可以像返回指针一样返回引用。

当函数返回引用时,它会返回对其返回值的隐式指针。这样,函数就可以用在赋值语句的左侧。例如,考虑这个简单的程序:

示例

 在线演示

#include <iostream>
#include <ctime>
using namespace std;
double vals[] = {10.1, 12.6, 33.1, 24.1, 50.0};
double& setValues( int i ) {
   return vals[i]; // return a reference to the ith element
}
// main function to call above defined function.
int main () {
   cout << "Value before change" << endl;
   for ( int i = 0; i < 5; i++ ) {
      cout << "vals[" << i << "] = ";
      cout << vals[i] << endl;
   }
   setValues(1) = 20.23; // change 2nd element
   setValues(3) = 70.8; // change 4th element
   cout << "Value after change" << endl;
   for ( int i = 0; i < 5; i++ ) {
      cout << "vals[" << i << "] = ";
      cout << vals[i] << endl;
   }
   return 0;
}

输出

Value before change
vals[0] = 10.1
vals[1] = 12.6
vals[2] = 33.1
vals[3] = 24.1
vals[4] = 50
Value after change
vals[0] = 10.1
vals[1] = 20.23
vals[2] = 33.1
vals[3] = 70.8
vals[4] = 50

返回引用时,请注意被引用的对象不会超出作用域。因此,返回对局部变量的引用是非法的。但是,您可以始终返回对静态变量的引用。

int& func() {
   int q;
   //! return q; // Compile time error
   static int x;
   return x; // Safe, x lives outside this scope
}

更新于:2019年7月30日

289 次浏览

启动你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.