LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 790|回复: 3

const instance的问题

[复制链接]
发表于 2005-5-16 10:23:54 | 显示全部楼层 |阅读模式
写了些源码看看const object的特性。


  1. #include <iostream>
  2. #include <string>

  3. using namespace std;

  4. class computer
  5. {
  6.         private :
  7.                 string type;
  8.         public :
  9.                 computer(){}
  10.                 computer(string type_);
  11.                 void setType(string type_);
  12.                 string getType();
  13. };

  14.         computer::computer(string type_) : type(type_)
  15. {
  16. }

  17. void computer::setType(string type_)
  18. {
  19.         type = type_;
  20. }

  21. string computer::getType()
  22. {
  23.         return type;
  24. }

  25. int main()
  26. {
  27.         const computer a (string("lenovo"));
  28.         computer b;
  29.         b.setType("IBM");
  30.         cout<<"Test!"<<endl;
  31.         cout<<a.getType()<<endl
  32.                 <<b.getType()<<endl;
  33. }
复制代码


用g++编译报错曰:passing 'const computer' as 'this' argument of 'string computer::getType ()' discards qualifiers
用vc .net编译报错:不能将this指针从const computer转化为computer&

const类型的对象应该怎么用?一般在什么场合下用?
发表于 2005-5-16 11:44:21 | 显示全部楼层
getType() 函数声明与定义后加上 const
回复 支持 反对

使用道具 举报

发表于 2005-5-16 12:34:27 | 显示全部楼层
const的好处是这个函数不会修改对象,——编译检查,runtime error可以轻易的发现错误,
而且,这意味着没有RAW(Read after write), 仅有RAR,编译器可以作更加aggressive的优化。
回复 支持 反对

使用道具 举报

 楼主| 发表于 2005-5-16 14:22:52 | 显示全部楼层
Post by rickxbx
getType() 函数声明与定义后加上 const


我也正打算这么试呢。我原只见过处理输出的成员函数加const修饰。现在又开了眼界了,hoho
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表