使用用户定义的操作隐式转换为类型

问题描述 投票:-1回答:1

我想将用户定义的运算符用于类内部的类型:

class TWithUserDefinedOp
{
private: int a{42};
public: operator *(const TWithUserDefinedOp& other) { return a * other.a;}
};

class Wrap 
{
private: TWithUserDefinedOp a;
public: operator TWithUserDefinedOp() const { return a; }
}

现在,当我想要多个Wrap类时,我希望它能正常工作

Wrap a, b;
auto mul = a * b; //Error: Wrap does not define this operator or a conversion to a type acceptable to the predefined operator

现在,如果我更改换行以容纳整数类型:

 class WrapIntegral 
 {
 private: int a{42};
 public: operator int() const { return a; }
 }

现在可以进行乘法。

WrapIntergal a,b;
auto mulInt = a * b; // this works ok

[我在其他类似问题中读到,C++仅允许1级隐式转换。如果我计算正确,第一个示例中只有一个隐式转换。从Wrap到定义了TWithUserDefinedOpoperator *。我的误解是什么?我在这里做什么错?

c++ operator-overloading implicit-conversion
1个回答
0
投票

auto mul = a * b;

与]相同>

auto mul = a.operator(b);

隐式转换应用于参数,而不是运算符的左侧。否则,编译器将必须检查定义了*运算符的每个类型是否具有可行的转换,最终将导致歧义(因为不太可能只有一个匹配项)。

© www.soinside.com 2019 - 2024. All rights reserved.