在下面的代码中:
#include <iostream>
#include <initializer_list>
struct A
{
bool operator+(A a);
};
bool operator+(A, A)
{
return false;
}
int main()
{
A a, b;
std::cout << a + b << std::endl;
}
标准说 N3797:3/8 [basic]
:
Two names are the same if
— they are identifiers composed of the same character sequence, or
— they are operator-function-ids formed with the same operator, or
[...]
在这个例子中,我们定义并声明了两个具有相同运算符的运算符函数,因此这两个函数具有相同的名称。因此,第一个声明引入了名称,第二个声明定义了一个实体,用该名称表示。怎么了?
最佳答案
这两个函数的名称不同。第一个是 A::operator+(A)
,第二个是 operator+(A,A)
。因此,它们是两个不同的函数,实际上只定义了第二个。
毕竟,给类 Foo
一个名为 bar()
的方法与定义一个函数 bar(Foo)
是不一样的。为什么运算符应该有所不同?
关于c++ - 为什么以下运算符重载不明确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27221737/