C++运算符()括号 - 运算符类型()与类型运算符()
答
第一(int operator()
)是函数调用操作,果然对象插入函数对象,可调用的功能等。该特定运算符返回一个int
,参数部分丢失。
实施例:
struct Foo
{
int operator()(int a, int b)
{
return a + b;
}
};
...
Foo foo;
int i = foo(1, 2); // Call the object as a function, and it returns 3 (1+2)
另一个(operator int()
)是转换运算符。这个特定的对象允许隐式地(或者明确地说,如果声明为explicit
)转换为int
。它必须必须返回一个int
(或使用任何类型,用户定义的类型,如类或结构也可以使用)。
实施例:
struct Bar
{
operator int()
{
return 123;
}
};
...
Bar bar;
int i = bar; // Calls the conversion operator, which returns 123
的转换算子是一个参数的构造相反。
答
这是一个巨大的差异。
T operator()
是一个电话运营商,所以你可以“叫”你的类是这样的:
class stuff {
// init etc
int operator()() {
return 5;
}
};
auto A = stuff(); // init that
cout << A() << endl; // call the object
operator T()
是将您的类的对象键入T
,所以你可以这样做:
class stuff {
operator int() {
return 5;
}
};
auto A = stuff();
cout << int(A) << endl;
转换可能严格为explicit
,并且显式或隐式,如上所述。
他们正在做完全不同的事情。 –
'int operator()'是一个函数调用操作符声明,缺少一组圆括号,而'operator int()'是一个转换操作符声明。 – Pixelchemist
你最后的陈述是否意味着你知道答案,但是想知道语言标准的相关部分如何?函数调用操作符覆盖了[over.call],第13.5.4节,而转换操作符覆盖了标准的第12.3节[class.conv]。 – WhozCraig