const

一.const修饰成员变量

1.const修饰类数据成员必须要初始化

#include <iostream>
using namespace std;
class A
{
public: A() { cout << "const x = " << x << endl; } private: const int x; }; int main() { A a; return 0; }

上面代码没有对成员变量进行初始化,编译的时候会报如下错误

/home/zzz/Workspace/test/cplusplus/const.cpp: In constructor ‘A::A()’:
/home/zzz/Workspace/test/cplusplus/const.cpp:6:4: error: uninitialized const member in ‘const int’ [-fpermissive] A() ^ /home/zzz/Workspace/test/cplusplus/const.cpp:11:14: note: ‘const int A::x’ should be initialized const int x;

const成员初始化第一种在类内

#include <iostream>
using namespace std;
class A
{
public: A() { cout << "const x = " << x << endl; } private: const int x = 100; }; int main() { A a; return 0; }

const成员初始化第二种在初始化列表

#include <iostream>
using namespace std;
class A
{
public: A():x(100) { cout << "const x = " << x << endl; } private: const int x; }; int main() { A a; return 0; }

2.const修饰的数据成员可以在非const函数中使用,但不可以修改

 二.const修饰成员函数

(const可以修饰类成员函数不可以修饰全局函数)

const修饰函数以后承诺不改变,在本函数中不会发生,改变数据成员的行为

只能调用const成员函数

void foo()const
{
}

const修饰函数可以构成重载  

const构成的重载函数,非const对象,优先调用非const版本
const对象只能调用const版本
void foo() { } void foo()const { }


void foo(int& a, int& b)
{
}
void foo(const int& a, const int& b)
{
}

三.const修饰对象

const修饰对象,其内可以有非const数据成员,但不可修改。只能调用const成员函数

 

转载于:https://www.cnblogs.com/aelite/p/10410113.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值