gpt4 book ai didi

c++ - 成员函数的 const 修饰符如何影响重载决议?

转载 作者:可可西里 更新时间:2023-11-01 17:50:30 24 4
gpt4 key购买 nike

我有以下测试代码:

#include <string>
#include <iostream>

class CString
{
public:
CString(char const*) {}
};

class TestBed
{
public:
void Comparison(CString const&) { std::cout << "CString Overload" << std::endl; }
void Comparison(std::string const&) { std::cout << "std::string overload" << std::endl; }
};

int main()
{
TestBed tb;
tb.Comparison("Hello World");
}

此代码无法编译,因为对 Comparison() 的调用不明确。我期待这种行为。

但是,当我进行任一 Comparison() 重载时 const,如:void Comparison(std::string const&) constvoid Comparison(CString const&) const(但不是两者),代码编译并选择非常量重载。

重载解决规则非常复杂,我还没有看到任何描述 const 如何影响这种情况的内容。我的理解是:

  1. 首先选择参数完全匹配的函数
  2. 接下来尝试一级隐式转换

在这两种情况下,1 和 2 都是不明确的。有人可以解释一下吗?谢谢。

最佳答案

对于类方法,this 部分被认为是一个额外的参数。因此,如果您将 CString 设置为一个常量,那么就会设置重载:

Comparison(const TestBed&, CString const&) // (1)
Comparison(TestBed&, std::string const&) // (2)

对于(1),我们需要进行两次转换:一次const 转换,一次转换为CString。但是对于 (2),我们只需要进行一次转换:到 std::string。因此,(2) 是首选。

我们可以通过添加第三个函数来验证这一点,该函数对this 进行一次转换:

Comparison(const TestBed&, const char*)  // (3)

在这里,我们再次只有一个转换(在“第一个”参数中),因此重载集是不明确的。


在 [over.match.funcs] 中:

a member function is considered to have an extra parameter, called the implicit object parameter, which represents the object for which the member function has been called. For the purposes of overload resolution, both static and non-static member functions have an implicit object parameter, but constructors do not.

For non-static member functions, the type of the implicit object parameter is

— “lvalue reference to cv X” for functions declared without a ref-qualifier or with the & ref-qualifier

— “rvalue reference to cv X” for functions declared with the && ref-qualifier

where X is the class of which the function is a member and cv is the cv-qualification on the member function declaration. [ Example: for a const member function of class X, the extra parameter is assumed to have type “reference to const X”. —end example ]

During overload resolution, the implied object argument is indistinguishable from other arguments.

这就是我们为什么考虑 const TestBed&TestBed& 的原因。然后就是比较重载 (1)(2) 之间的转换序列。对于第二个参数,两个转换序列是相等的,但对于第一个参数,(2) 具有更好的转换序列(即 Exact)——这就是它毫无歧义地获胜的原因。

关于c++ - 成员函数的 const 修饰符如何影响重载决议?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27972910/

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