我有一个定义类型 Coordinates
,如下所示:
#include <array>
using Coordinates = std::array<double, 3>;
我为此调用了以下运算符重载函数:
Coordinates operator+(const Coordinates& lhs, const Coordinates& rhs);
Coordinates operator*(const Coordinates& lhs, const Coordinates& rhs);
两个重载都有效,所以如果我有 2 个 Coordinates
变量:
C1 = { 1., 2., 3.}
和
C2 = { 1., 2., 3. }
C1+C2
返回 { 2., 4., 6.}
C1*C2
返回 { 1., 4., 9.}
现在我想定义一个 *+
运算符:
C1*+C2
返回 1。 + 4. + 9.
或 14.
我尝试了以下实现:
Coordinates operator*+(const Coordinates& lhs, const Coordinates& rhs)
{
return lhs[0] * rhs[0] + lhs[1] * rhs[1] + lhs[2] * rhs[2];
}
但是,*+
不是预定义的运算符。然后我尝试了这种格式:
Coordinates operator "" *+(const Coordinates& lhs, const Coordinates& rhs)
{
return lhs[0] * rhs[0] + lhs[1] * rhs[1] + lhs[2] * rhs[2];
}
但我明白了:无效的文字运算符名称
。这是可以理解的:
double operator "" _d_(const Coordinates& lhs, const Coordinates& rhs)
{
return lhs[0] * rhs[0] + lhs[1] * rhs[1] + lhs[2] * rhs[2];
}
_d_
代表点积中的点,但现在我收到此错误 too many parameters for this literal
。是否可以为点积定义一个运算符,或者我是否必须编写一个 dot()
函数?
最佳答案
您只能为您的类型重载 38 个现有运算符。此处列出:https://en.cppreference.com/w/cpp/language/operators
op
- any of the following 38 (until C++20) 39 (since C++20) operators:
+
-
*
/
%
^
&
|
~
!
=
<
>
+=
-=
*=
/=
%=
^=
&=
|=
<<
>>
>>=
<<=
==
!=
<=
>=
<=>
(since C++20)&&
||
++
--
,
->*
->
(
)
[
]
文字运算符处理单个参数并将文字(如 42、“foobar”)转换为对象。由于您已经拥有对象,因此您必须使用运算符重载。选择任何可用的。
关于c++ - 创建一个接受 2 个输入参数的文字运算符函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54443677/