您的位置:首页 > 其它

指针与const之间的组合,写了个例子温习一下

2016-11-11 19:04 351 查看
[cpp] view
plain copy

 print?

#include <iostream>  

  

class A  

{  

public:  

    A()  

    {  

        this->i = 1;  

    }  

    int get() const  

    {  

        return this->i;  

    };  

    void set(int i)  

    {  

        this->i = i;  

    };  

private:  

    int i;  

};  

  

int main()  

{  

    // 指针常量, 必须在声明时进行初始化。  

    A *const p = new A;  

    std::cout << p->get() << std::endl;  

    p->set(3);  

    // p = p + 1; 编译就报错了。  

    std::cout << p->get() << std::endl;  

  

    // 指向常量的指针  

    const A *p1 = new A;  

    std::cout << p1 << std::endl;  

    p1 = p1 + 1;  

    // p1->set(3); 编译就报错了。  

    std::cout << p1 << std::endl;  

      

    // 指向常量的常指针  

    const A *const p2 = new A;  

    std::cout << p2->get() << std::endl;  

  

    return 0;  

}  



总结:const修饰的是什么,什么就是常量
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: