I am learning the 'const' when passing parameters in function.
I suppose to put 'const' in different places to check what error I might get. Please give me some advices why it reports error if I move 'const' before the variable '&number'.
If I put 'const' before the variable '&number', it works fine. Why?
Thank you.
//error message
gongzhen@gongzhen-PC ~/Source-3rd/Ch07
$ g++ -o const_declaration const_declaration.cpp
const_declaration.cpp: In function `int main()':
const_declaration.cpp:15: error: invalid initialization of non-const reference o
f type 'int&' from a temporary of type 'int'
const_declaration.cpp:7: error: in passing argument 1 of `char* function1(int&)'
const_declaration.cpp:17: error: invalid initialization of non-const reference o
f type 'int&' from a temporary of type 'int'
const_declaration.cpp:7: error: in passing argument 1 of `char* function1(int&)'
const_declaration.cpp:21: error: invalid initialization of non-const reference o
f type 'int&' from a temporary of type 'int'
const_declaration.cpp:7: error: in passing argument 1 of `char* function1(int&)'
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
#include <iostream>
using namespace std;
//Report error: assignment of readly-only location if adding const before function type
//const char *function1()
char *function1(int &number)
{
cout<<"number"<<number<<endl;
return "Some text";
}
int main()
{
//Report error: assignment of readly-only location if adding const before function type
function1(3)[1]='a';
for(int i=0; i<9; i++){
cout<<""<< function1(4)[i]<<endl;
}
//The program could crash if it accidentally tried to alter the
//value doing
function1(5)[1]='a';
return 0;
}
|