在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
}
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP