gpt4 book ai didi

c++ - 在 c++ 中,为什么编译器在 const 也可以工作时选择非常量函数?

转载 作者:IT老高 更新时间:2023-10-28 22:00:23 27 4
gpt4 key购买 nike

例如,假设我有一个类(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;
};

在代码的其他地方,我有这样的东西:

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

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

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

最佳答案

两个答案浮现在脑海:

  1. 非常量版本更匹配。

  2. 如果它为非常量情况调用 const 重载,那么在什么情况下它会曾经调用非常量重载?

您可以通过将 a 强制转换为 const Foo * 来使其使用其他重载。

编辑:来自C++ Annotations

Earlier, in section 2.5.11 the conceptof function overloading wasintroduced. There it noted that memberfunctions may be overloaded merely bytheir const attribute. In those cases,the compiler will use the memberfunction matching most closely theconst-qualification of the object:

关于c++ - 在 c++ 中,为什么编译器在 const 也可以工作时选择非常量函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/164102/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com