2008 July 10th Thursday (七月 十日 木曜日)

本文探讨了C++中常量引用的使用方法及其在不同情况下的行为表现。通过具体的代码示例,解释了如何正确地使用const Str& rs = cs这样的表达式,并展示了在成员函数中const关键字的作用及限制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 ...
const Str cs(8);
Str& rs = cs;  //error, rs can't refer to cs.
...

  Because the "cs" is a const Str instance, a Str reference is not allowed to refer to it.

...
const Str cs(8);
const Str& rs = cs;  //add const, ok.
...

  Yes, a const Str reference can refer to a const Str instance.

By the way, there another way to slove the above error problem.

...
Str cs(8);  // removed const
Str& rs = cs;  //ok
...

  A non-const Str reference can refer to a non-const Str instance.

  What is more!

class C{
public:
  ...
  void fun() const {};
  ...
private:
  ...

}

  A const function is only a member of a class.  The const function is meant that it should
be used for a constants or a non-constants.  A non-const function only can be used for a non-constant.
For example.

  const C cc;
 
  cc.fun(); //ok
 
  const C nc;
 
  nc.fun(); //error.


  More example.

#include <iostream>

using namespace std;

class Str{
public:
Str(){
data = 0;
len = 0;
}

Str(int d){
data = d;
len = d * 2;
}

int getData() const{
return data;
}

int getData(){
cout<<"non-const getData()"<<endl;
return data;
}

int length() const{
return len;
}

int length(){
cout<<"non-const length()"<<endl;
return len;
}

int add(const Str& s) const{
int ret = data * s.getData();

/*Str *sp = const_cast<Str*>(&s);
sp->clear();*/

return ret;
}
private:
mutable int data;
mutable int len;

friend void clear(const Str& s);
};

void clear(const Str& s) {
s.data = 0;
s.len = 0;
}

int main(){
Str s(5);

//cout<<s.length()<<" "<<s.getData()<<endl;

const Str cs(8);

cout<<cs.length()<<" "<<cs.getData()<<endl;

cout<<s.add(cs)<<endl;

clear(cs);
cout<<cs.length()<<" "<<cs.getData()<<endl;

Str& rs = cs;

return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值