C++ 关于const

编程环境:win10,vs2017

 

定义常量

//const int b;  //常量没有初始化  编译器报错: 错误(活动) E0257    常量 变量 "b" 需要初始值设定项

const int b = 1;  //定义常量b,初始化为1

 

常量的值是不能被修改的,以下试图修改常量的值的代码,编译器会报错。

 

直接修改常量的值

const int b = 1;

//b = 3;  //错误  C3892    “b” : 不能给常量赋值

 

通过引用修改常量的值

const int b = 1;

//int& rb = b;  //编译器报错:错误(活动) E0433    将 "int &" 类型的引用绑定到 "const int" 类型的初始值设定项时,限定符被丢弃

const int& crb = b;

//crb = 3;  //编译器报错: 错误 C3892    “cpb” : 不能给常量赋值

 

通过指针修改常量的值

const int b = 1;

//int& rb = b;  //编译器报错:错误(活动) E0433    将 "int &" 类型的引用绑定到 "const int" 类型的初始值设定项时,限定符被丢弃

const int& crb = b;

//crb = 3;  //编译器报错: 错误 C3892    “cpb” : 不能给常量赋值

 

指针本身是常量

int c = 1;

int d = 3;

int * const e = &c;

*e = 9;

//e = &d;  //编译器报错: 错误  C3892    “e” : 不能给常量赋值

 

常量与类

namespace ds06

{

    struct DsSize

    {

    public:

         DsSize(const int&width, const int&height) :width(width), height(height) {}

 

    public:

         int SetWidth(const int& width)

         {

             this->width = width;

         }

 

         const int& GetWidth() const  //

         {

             return width;

         }

 

         int SetHeight(const int& height)

         {

             this->height = height;

         }

 

         const int& GetHeight() const  //

         {

             return height;

         }

 

    private:

         int width;

         int height;

    };

 

    //重载运算符 << ,不能在类的内部定义,只能放在类的外部定义。

    ostream& operator << (ostream& out, const DsSize& size)  //

    {

         out << "Address=0x" << &size << " Width=" << size.GetWidth() << " Height=" << size.GetHeight();

         return out;

    }

 

    //测试程序

    void testDsSize1()

    {

         const DsSize s1(1920,1080);  //

         cout << "s1 : " << s1 << endl;  //

    }

}

说明:

const DsSize s1(1920,1080);   //

上面一行定义了一个常量对象,为此在类的定义中,需要在多处添加const关键字。

const int& GetWidth() const  //④   vs2017 需要加两个const

const int& GetHeight() const  //

 

重载 << 运算符定义中的const ,可以使下面的输出语句编译通过。

cout << "s1 : " << s1 << endl;  //

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值