其实,不论是参数还是返回值,道理都是一样的,参数传入时候和函数返回的时候,初始化const变量
const 和 参数
1、函数形参表里没有const
#include <iostream>
using namespace std;
void f (int a)
{
++a;
cout<<a<<endl;
}
int main()
{
int a = 5;
f( 3 ); //括号里是字面常量还是变量都可以
2、符号常量——值传递
#include<iostream>
using namespace std;
void f (const int a)
{
//++a; 错误,因为a是符号常量,所以它的值不能再改变了
cout<<a<<endl;
}
int main()
{
int a = 5;
f( a ); //括号里是字面常量还是变量都可以
}
3、指向const的指针——指针传递
#include <iostream>
using namespace std;
void f (const int * p) //指向const的指针
{
//++(*p) ; 当然是错误的,不能通过该指针来修改变量的值
cout<<*p<<endl;
}
int main()
{
int a = 5;
f(&a);
}
4、const指针——指针传递
#include <iostream>
using namespace std;
void f (int * const p) //const指针
{
++(*p) ; //正确,可以通过该指针来修改变量的值
// int x=0; p=&x; 错误,不能再改变const的指向
cout<<*p<<endl;
}
int main()
{
int a = 5;
f(&a);
}
5、指向const的const指针——指针传递
#include <iostream>
using namespace std;
void f (const int * const p) //指向const的const指针
{
// ++(*p) ; 错误,不能通过该指针来修改变量的值
// int x=0; p=&x; 错误,不能再改变const的指向
cout<<*p<<endl;
}
int main()
{
int a = 5;
f(&a);
}
6、常引用——引用传递
#include <iostream>
using namespace std;
void f (const int & a) //既有 const ,又有 & 的话,是常引用
{
//++a ; 当然是错误的
cout<<a<<endl;
}
int main()
{
int a = 5;
f(a ); //这个既可以是变量也可以是字面常量 ,因为常引用的初始化值既可以是变量也可以是字面常量
}
const 和 返回值
规律:
①在返回值中一般来说,const后的都是类,内置数据类型前加const没有什么意义。
②返回值中有const说明该返回值返回以后不能做左值,即其值不能修改了。
#include <iostream>
using namespace std;
class A
{
public:
A (): x("hello"){}
const string f()
{return x;}
private :
string x;
};
int main ()
{
string s1="xx", s2 = "kk";
A ob1;
cout<<ob1.f()<<endl;
// s2=ob1.f() = s1;//要是成员函数f()返回值中没有const的话,这个句子就是合法的
cout<<s2<<endl;
}
.
浙公网安备 33010602011771号