|
|
写了些源码看看const object的特性。
- #include <iostream>
- #include <string>
- using namespace std;
- class computer
- {
- private :
- string type;
- public :
- computer(){}
- computer(string type_);
- void setType(string type_);
- string getType();
- };
- computer::computer(string type_) : type(type_)
- {
- }
- void computer::setType(string type_)
- {
- type = type_;
- }
- string computer::getType()
- {
- return type;
- }
- int main()
- {
- const computer a (string("lenovo"));
- computer b;
- b.setType("IBM");
- cout<<"Test!"<<endl;
- cout<<a.getType()<<endl
- <<b.getType()<<endl;
- }
复制代码
用g++编译报错曰:passing 'const computer' as 'this' argument of 'string computer::getType ()' discards qualifiers
用vc .net编译报错:不能将this指针从const computer转化为computer&
const类型的对象应该怎么用?一般在什么场合下用? |
|