C++ 运算符 () 括号 - 运算符 Type() 与 Type 运算符()

Bob*_*Bob 7 c++

如果有的话有什么区别?

例如:int operator()operator int()

我正在寻找“官方”C++ 文档的答案。

Som*_*ude 10

第一个( 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)
Run Code Online (Sandbox Code Playgroud)

other( operator int()) 是转换运算符。这一特定的允许将对象隐式(或显式地,如果声明explicit)转换为int. 它必须返回一个int(或者使用任何类型,也可以使用用户定义的类型,例如类或结构)。

例子:

struct Bar
{
    operator int()
    {
        return 123;
    }
};

...

Bar bar;
int i = bar;  // Calls the conversion operator, which returns 123
Run Code Online (Sandbox Code Playgroud)

转换运算符与单参数构造函数相反。