c++中使用const关键字的联系区别
来源:互联网 发布:那些公司用three.js 编辑:程序博客网 时间:2024/06/05 23:58
答:const void fun(){};和void const fun(){};两个相同。
如果采用"按址传递方式"的函数返回值加const 修饰,那么函数返回值(即地址)的内容不能被修改,该返回值只能被赋给加const 修饰的同类型指针。
如果采用"按值传递方式"的函数返回值加const 修饰,由于函数会把返回值复制到外部临时的存储单元中,加const 修饰没有任何价值。
所以不要尽量不要把int fun2();写成const int fun2(); 因为没意义。
例:
#include<iostream>
using namespace std;
int num=10; //全局变量
const int *fun1(){ //按址传递
return # //返回地址
}
const int fun2(){ //按值传递 //最好直接写int fun2()
return num;
}
int main()
{
const int *fun1();
// int *t1=fun1(); //错误,必须是const型
const int *t1=fun1();
// *t1=20; //错误,按址传递,不能修改其指向变量或常量的值
cout<<"const int *fun1() :\t"<<*t1<<endl;
const int fun2(); //最好直接声明成int fun2()
int t2=fun2(); //非const变量可以更改函数返回值
const int t3=fun2();
t2 += 10; //按值传递,可以修改返回值
cout<<"const int fun2() :\t"<<t2<<endl;
return 0;
}
运行效果:
2、void fun() const{};类的成员函数后面加 const,表明这个函数不可以对这个类对象的数据成员(准确地说是非static数据成员)作任何改变。
例:
#include<iostream>
using namespace std;
class R
{
public:
R():num1(1){}
int sum1(int a)const
{
// num1=10; //错误,不可以修改非static数据成员
return a+num1;
}
int sum2(int a)const
{
num2=2; //正确,修改static数据成员
return a+num2;
}
int sum3(int a) //没有const
{
num1=10; //正确,修改非static数据成员
num2=20; //正确,修改static数据成员
return a+num1+num2;
}
private:
int num1;
static int num2;
};
int R::num2=0;
int main()
{ R t;
cout<<"t.sum1(1):\t"<<t.sum1(1)<<endl;
cout<<"t.sum2(1):\t"<<t.sum2(1)<<endl;
cout<<"t.sum3(1):\t"<<t.sum3(1)<<endl;
return 0;
}
运行效果:
- c++中使用const关键字的联系区别
- 嵌入式C中const关键字的使用
- C++、C#中 abstract 与 virtual关键字的区别联系
- C++、C#中 abstract 与 virtual关键字的区别联系
- C语言与C++中static,const 关键字的区别
- C和C++中const关键字的区别
- C# 中使用readonly关键字和const的区别
- C语言和C++中const关键字使用的异同
- C中const关键字
- C中const关键字
- c语言中const 关键字的理解
- C语言中const关键字的用法
- C语言中const关键字的用法
- C语言中const关键字的用法
- C语言中const关键字的用法
- C语言中const关键字的用法
- C语言关键字之const的使用
- C#中readonly关键字与const关键字的区别
- Linux--进程管理、查询与压缩
- Python基础教程
- SQL注入攻击与防御
- 自定义View,随机画点
- How JavaScript Event Delegation Works
- c++中使用const关键字的联系区别
- heap和stack的差别
- 从三国的人物身上我们能学到些啥?
- Project Euler problem 42
- 在VC中为应用程序添加图形超链接功能
- 卷积神经网络----无监督特征学习
- 编程的朋友们用的着的键盘键值汇总
- poj 1845 Sumdiv
- 【次小生成树】环切性质