本文介绍了如何在C ++中丢弃const的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

这是我要尝试做的事情,我不能做:

This is what I'm trying to do and I can't:

#include <string>
using namespace std;
class A {
public:
  bool has() const { return get().length(); }
  string& get() { /* huge code here */ return s; }
private:
  string s;
};

我得到的错误是:

passing ‘const A’ as ‘this’ argument of
‘std::string& A::get()’ discards qualifiers

我了解问题所在,但如何解决它?我真的需要 has() const 。谢谢。

I understand what the problem is, but how can I fix it? I really need has() to be const. Thanks.

推荐答案

添加第二个 get()的重载:

string const & get() const { return s; }

将在 const 上调用类 A 的类型对象。

That will be called on a const typed object of class A.

在实践中,我更喜欢仅添加 const 类型的访问器,然后将修改完全保留在类的内部,甚至完全避免进行修改。例如,这意味着使用方法 DoUpdateLabel(){/ *使用s * /} 进行某些操作,而不是公开内部函数。这样做的好处是,在很多情况下,您可以避免复制访问器。

In practice, I prefer adding only const-typed accessors, and then keeping modifications entirely internal to the class or even avoid them entirely. For example, that means having a method DoUpdateLabel(){/*do something with s*/} rather than expose the internals. That has the nice side effect that you can avoid duplicating accessors in many cases.

如果您绝对必须通过访问器进行修改,并且您也不想使用额外的const包装器,您可以使用 const_cast<>

If you absolutely must have modification via accessors and you also don't want an extra const wrapper, you can use const_cast<>:

bool has() const { return const_cast<A*>(this)->get().length(); }

但是,如果 get()有副作用和 has()被声明为 const ,这是否是您真正想要的行为值得怀疑。

However, if get() has side-effects and has() is declared const, it's questionable whether this is behavior you really want.

这篇关于如何在C ++中丢弃const的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 10:05