在c ++中,为什么编译器选择非const函数时const也会工作? [英] In c++, why does the compiler choose the non-const function when the const would work also?

查看:99
本文介绍了在c ++中,为什么编译器选择非const函数时const也会工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,假设我有一个类:

For example, suppose I have a class:

class Foo
{
public:
    std::string& Name()
    {
        m_maybe_modified = true;
        return m_name;
    }

    const std::string& Name() const
    {
        return m_name;
    }
protected:
    std::string m_name;
    bool m_maybe_modified;
};

而在代码中的其他地方,我有这样的:

And somewhere else in the code, I have something like this:

Foo *a;
// Do stuff...
std::string name = a->Name(); // <-- chooses the non-const version

有人知道为什么编译器会选择非const版本在这种情况下?

Does anyone know why the compiler would choose the non-const version in this case?

这是一个有点麻烦的例子,但我们试图解决的实际问题是定期自动保存一个对象,如果它已经改变,并且指针必须是非常量,因为它可能在某个点被改变。

This is a somewhat contrived example, but the actual problem we are trying to solve is periodically auto-saving an object if it has changed, and the pointer must be non-const because it might be changed at some point.

推荐答案

有两个答案:


  1. 非const版本是更紧密的匹配。

  1. The non-const version is a closer match.

如果它为非常量的情况调用const重载,

If it called the const overload for the non-const case, then under what circumstances would it ever call the non-const overload?

你可以得到它通过将 转换为 const Foo * 来使用其他重载。

You can get it to use the other overload by casting a to a const Foo *.

修改:从 C ++注释


早些时候,在2.5.11节中,函数重载的概念
是引入的
。在这里注意到成员
函数只能通过
的const属性重载。在这些情况下,
编译器将使用成员
函数 最接近地匹配对象的
const-qualification:
p>

Earlier, in section 2.5.11 the concept of function overloading was introduced. There it noted that member functions may be overloaded merely by their const attribute. In those cases, the compiler will use the member function matching most closely the const-qualification of the object:

这篇关于在c ++中,为什么编译器选择非const函数时const也会工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆