条款03:尽可能使用const

本文详细探讨了C++中const关键字在修饰指针、迭代器、函数返回值以及const成员函数时的含义和应用,区分了physicalconstness和logicalconstness的概念,并提供了实例来说明如何避免const和非const成员函数中的重复行为。
摘要由CSDN通过智能技术生成

目录

1.cosnt修饰指针

2.cosnt修饰迭代器

3.const修饰函数返回值

4.const成员函数

1.physical constness (对象物理空间不能改变)

2.logical constness

5.const和非const成员函数中避免重复


1.cosnt修饰指针

char greeting[] = "hello"

char * p  = greeting;,指针可修改,指向内容可以修改。

cosnt char *p = greetng; ,指针可修改,指向内容不可以修改。

char * cosnt p = greetng;,指针不可修改,指向的容可以修改。

const char * const p = greeting;,指针不可修改,指向内容不可以修改。

const出现在 * 的左边修饰指针指向的内容,出现在 * 的右边修饰指针本身。

fun1(const A * pa)和fun2( B const * pb) pa和pb都是指向的内容不可改变。

2.cosnt修饰迭代器

迭代器是由指针塑模出来了,修饰迭代器就相当于修饰指针本身。

vector<int> vec;

const vector<int> :: iterator iter = vec.begin();

*iter = 20;正确 可以修改

iter++;错误指针本身不可以修改

如果想要指向的内容不可修改应该使用const迭代器

vector<int>::const_iterator Citer = vec.begin();

*iter = 20;错误const_iterator迭代器内容不可修改

iter++;正确指针本身可以修改

3.const修饰函数返回值

如果一个函数返回值是不需要改动的,一定要加上const,防止用户未确定的行为。

class Rational {.......};

例: const Rational operator*(const Rational &lhs,const Rational &rhs)

Rational a,b,c;

(a * b) = c;//在a * b的结果上调用operator=这个是一个无意义的行为,内置类型也不支持这样操作,在运算符重载的时候,要于内置类型一致。

4.const成员函数

针对const成员函数主要有两种说法

1.physical constness (对象物理空间不能改变)

这种说法主张const 成员函数,不可以更改成员变量的任何非non-static变量。

一个更改了指针所指物,成员函数不能算作const,但是如果所指物,不隶属于对象,称为physical constness 

例:

class  A
{

 .......................
public:
    char& operator[](size_t postion) const //physical constnes声明
    {
        return _str[postion];
    }

private:
    char* _str;
};

int main()
{
    const A a ("hello");
    a[0] = 'j';

}

这样就得到了jello

编译器检查采用的是physical constness检查,但是编写程序要用"概念上的常量性".

2.logical constness

这一派主张const成员函数可以修改他所处理对象的一部分bits

例:

class B
{
public:
    size_t modlenth(int newlen) const
    {
        _lenth = newlen;
    }

private:
    char* _str;
    mutable size_t _lenth;
};

 

只需要在成员变量的前面加上mutable(可修改的)就可以释放physical constness的约束

5.const和非const成员函数中避免重复

class C
{
public:
    const char& operator[](size_t postion) const
    {
        return _str[postion];
    }

    char& operator[](size_t postion)
    {
        return const_cast<char&>( //3.把const成员函数返回值的const去掉

                                                     static_cast <const C&>(*this)//1.先把转化为const对象

                                                                                        [postion]);//2.调用const成员函数
    }

private:
    char* _str;
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值