20. 不可修改的对象

来源:互联网 发布:网络销售授权书怎么写 编辑:程序博客网 时间:2024/05/22 10:47

建议:
传对象,需要花费堆栈。
传地址,担心别人修改指针多指向的内容.
1. 传参数 void f(const int *x);
2. const Currency the_raise(42,38); //对象Currency里面的值是不能被修改的. 这样肯定是不行的,建议成员函数加const 相当于this 是const

class Data {}int Data::get_day() const{   day++; //出错, 原因是加了const  int Data::get_day() const   set_day(12); //出错 原因是加了const int Data::get_day() const}
class A{     int i;   public:     A():i(0) {}     void f() { cout << "f()" << endl; }      //void f(A* this) { cout << "f()" << endl;     void f() const { cout << "f() const" << endl;} //const其实表示的是this     //void f(const A* this) { cout << "f() const" << endl;};int main(){   const A a;   a.f(); //f() const   return 0;}
class A{   const int i; //必须初始化,方式是在构造函数进行初始化};
class HasArray{   const int size;   int array[size]; //error};class HasArray{   enum { size = 100 };   int array[size]; //ok};
原创粉丝点击