gpt4 book ai didi

C++ 编译器选择了类成员函数的错误重载

转载 作者:行者123 更新时间:2023-11-30 02:08:17 28 4
gpt4 key购买 nike

我有这个代码:

template <class T>
class Something
{
T val;
public:
inline Something() : val() {}
inline Something(T v) : val(v) {}
inline T& get() const { return val; }

inline Something& operator =(const Something& a) { val = a.val; return *this; }
};

typedef Something<int> IntSomething;
typedef Something<const int> ConstIntSomething;

class Other
{
public:
IntSomething some_function()
{
return IntSomething(42);
}

ConstIntSomething some_function() const
{
return ConstIntSomething(42);
}
};

void wtf_func()
{
Other o;
ConstIntSomething s;
s = o.some_function();
}

但是,编译器在 wtf_func() 中选择了错误的 Other::some_function() 重载(即非常量重载)。我怎样才能解决这个问题?请注意,由于某些原因,我无法更改 Other::some_function() 的名称。

最佳答案

o 不是 const 限定的,因此选择非 const some_function。如果要选择 const 限定的重载,则需要将 const 限定符添加到 o 中:

Other o;
Other const& oref(o);
ConstIntSomething s;
s = oref.some_function();

当发生重载解析时,编译器仅查看o.some_function()子表达式;它不会查看函数调用周围的上下文来决定选​​择其他内容。此外,重载决策期间不考虑成员函数的返回类型。

请注意,将 IntSomething 隐式转换为 ConstIntSomething 可能更有意义,可以使用 operator ConstIntSomething() 重载 IntSomething (不太好)或在 ConstIntSomething 中使用非显式 ConstIntSomething(IntSomething const&) 构造函数(更好)。

关于C++ 编译器选择了类成员函数的错误重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7082963/

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