const and function


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
  string test (const string &hey) //what dose const do here
{
	return hey;


}
string t (string &hey)
{
	return hey;

}
int main ()
{
	
	string h =  test("hi");
	cout << h;
	h = t("hi"); //doesnt work
	cout<<h;

}
Last edited on
"doesn't work" is inaccurate.

A compiler says:
 In function 'int main()':
17:12: error: invalid initialization of non-const reference of type 'std::string& {aka std::basic_string<char>&}' from an rvalue of type 'const char*'
7:8: note: in passing argument 1 of 'std::string t(std::string&)' 


Initialization? Lets give a string object then:
1
2
	const std::string foo( "hi" );
	h = t( foo );

Not better:
 In function 'int main()':
18:13: error: invalid initialization of reference of type 'std::string& {aka std::basic_string<char>&}' from expression of type 'const string {aka const std::basic_string<char>}'
7:8: note: in passing argument 1 of 'std::string t(std::string&)' 

Do you notice a theme?
Topic archived. No new replies allowed.