Home >Backend Development >C++ >How to solve the C++ compilation error: 'invalid initialization of reference of type 'type&' from expression of type 'type''?
Solution to C compilation error: 'invalid initialization of reference of type 'type&' from expression of type 'type'', how to solve it?
Problem background:
In C programming, we sometimes encounter compilation errors. One of them is the error message "invalid initialization of reference of type 'type&' from expression of type 'type'", that is, a type mismatch occurs when initializing data of reference type.
The cause of this error is an attempt to initialize an unmodifiable temporary object or literal to a non-const reference variable. The nature of reference types in C requires that the referenced object must have constant existence.
Solution:
int main() { int value = 10; int& ref = value; // 正确示例:将一个可修改的lvalue赋给引用变量 return 0; }
int main() { int& ref = 10; // 错误示例:试图将字面值初始化为非常量引用变量 return 0; }
The correct approach is to save the literal value in a variable with constant existence and then assign it to the reference variable. The code example is as follows:
int main() { int value = 10; const int& ref = value; // 正确示例:将一个具有恒定存在性的变量的值赋给引用变量 return 0; }
int main() { const int value = 10; int& ref = value; // 错误示例:试图将常量赋给非常量引用变量 return 0; }
The correct approach is to assign the constant to a non-const variable with constant existence and assign it to a constant reference variable. The code example is as follows:
int main() { const int value = 10; const int& ref = value; // 正确示例:将一个常量赋给常量引用变量 return 0; }
Conclusion:
In C programming, when we encounter the compilation error "invalid initialization of reference of type 'type&' from expression of type 'type'", we need to pay attention to the reference The nature of the type requires that the referenced object be a modifiable lvalue. Avoid assigning temporary objects or literal values to non-const reference variables, and use const references when possible to handle constant objects. By properly initializing the reference variables, we were able to resolve this compilation error.
The above is the detailed content of How to solve the C++ compilation error: 'invalid initialization of reference of type 'type&' from expression of type 'type''?. For more information, please follow other related articles on the PHP Chinese website!