我遇到了一个奇怪的 C++ 运算符。
class Number {
..
operator unsigned short () const;
};
我称这个运算符为: 一个号码(..); unsigned short b = a.operator unsigned short();
这行得通,但我不明白它是如何工作的。
首先,这个运算符没有返回值。 秒,a.operator unsigned short() 对我来说真的很奇怪。什么是更好的称呼方式?
如果我打电话: 无符号短 b = a;接线员会接到电话吗?有什么 C++ 标准可以说明这一点吗?
最佳答案
该函数是用户定义的转换运算符。更多详细信息,请访问 http://en.cppreference.com/w/cpp/language/cast_operator .
你说,
this operator don't have a return value. seconds,
用户定义的转换运算符的返回值是显式类型。在您的例子中,返回类型是 unsigned short
。
你问:
What is a better way to call this?
您可以进行显式转换以调用该函数。
Number n;
unsigned short s = (unsigned short)v;
当编译器需要转换时也会调用它。
void foo(unsigned short s) {}
Number n;
foo(n); // Number::operator unsigned short() is called to cast
// n to an unsigned short.
你问:
if I call :
unsigned short b = a;
does the operator will get called? is there any c++ standard to say about this?
是的。调用用户定义的运算符函数。
以下是 C++ 标准草案 (N3337) 中的相关部分:
12.3.2 Conversion functions
1 A member function of a class
X
having no parameters with a name of the form...
[ Example:
struct X { operator int(); }; void f(X a) { int i = int(a); i = (int)a; i = a; }
In all three cases the value assigned will be converted by X::operator int(). — end example ]
关于c++ - 奇怪的 c++ 运算符(运算符 unsigned short()),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25598299/