• 条款三 尽可能使用const


    1.const 修饰指针

    char greeting[] = "hello";
    char *p = greeting; //non-const pointer,non-const data
    const char *p = greeting; //non-const pointer,const data
    char* const p = greeting; //const pointer,non-const data
    const char* const p = greeting; //const pointer,const data
    

     

    2.STL迭代器

    vector<int> vec;
    const vector<int>::interator iter = vec.begin(); //iter指向的值可以改变,但指向的地址不可改变,++iter是错误的 
    vector<int>::const_iterator citer = vec.begin(); //citer指向的值不可改变,但地址可以改变,++citer是对的,但(*citer)++是错误的

    3.const可以和函数返回值,参数以及函数本身产生关联,如一个类里的重载操作符函数
    class Rational{.....};
    const Rational operator* (const Rational& lhs,const Rational& rhs); //重载操作符*函数
    const返回值为const类型可以防止如下面情况发生
    Rational a,b,c;
    (a * b) = c;
    //把c对象赋给a*b的结果,这个情况一般是无意中发生,如if((a * b) = c),也许本意是判断相等的==,但漏写了一个=,
    //要是*操作返回类型不是const,则不会报错,所以很难查找到出错的地方

    4.类的成员函数

    class Test
    {
    .....
    //这两个函数是互为重载
    //被const类对象调用,函数无法改变non-static成员变量的值,可以改变static变量的值
    const char& operation[] (size_t pos) const 
    {
    str = "world" ; //错误
    str_1 = "world" ; //正确
    str_2 = "world" ; //正确
    return str[pos];
    }
    
    char& operation[] (size_t pos) {return str[pos];}
    //被non-const类对象调用,可以改变成员变量
    
    private:
    string str;
    mutable string str_1; //mutable使得const约束的成员函数也可以改变str_1的值
    static string str_2; //static成员变量,可以初始化(vc6.0不支持)
    };
    
    string Test::str_2; //这步是必须的,可以初始化,也可以不必
    

    ---------------------------------------------------------------------------------------------

    #include <iostream>
    #include <string>
    using namespace std;
    class Test
    {
    public:	
    	void print() const 
    	{
    		cout << "const fun" << endl;
    		//str = "hello world";   //出错
    		str_2 = "world";
    		str_1 = "hello";
    		cout << str_1 << "  " <<str_2 << endl;
    	}	
    	void  print() {cout << "non-const fun" << endl;}
    private:
    	string str;
    	mutable string str_1;
    	static string str_2;
    };
    string Test::str_2 ;
    int _tmain(int argc, _TCHAR* argv[])
    {
        const  Test t;
        t.print();
        return 0;
    }
    

     

     


  • 相关阅读:
    android gradle 打包命令
    android RRO
    android adb 常用命令
    mui执行滑动事件: Unable to preventDefault inside passive event listener
    获取 input[type=file] 文件上传尺寸
    MySQL:You can't specify target table for update in FROM clause
    input标签中autocomplete="off" 失效的解决办法
    @media属性针对苹果手机写法
    centos7 下mysql5.7修改默认编码格式为UTF-8
    使用Mui加载数据后a标签点击事件失效
  • 原文地址:https://www.cnblogs.com/bizhu/p/2597743.html
Copyright © 2020-2023  润新知