20. 不可修改的对象

建议:
传对象,需要花费堆栈。
传地址,担心别人修改指针多指向的内容.
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
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值