c++ - 奇怪的 c++ 运算符(运算符 unsigned short())

标签 c++ operator-overloading

我遇到了一个奇怪的 C++ 运算符。

http://www.terralib.org/html/v410/classoracle_1_1occi_1_1_number.html#a0f2780081f0097af7530fe57a100b00d

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/

相关文章:

c++ - C++ 中的被动对象

C++从后面删除节点——单链表

C# GetHashCode/Equals 覆盖未调用

c++ - 重载 << 时返回对局部变量的引用

c++ - Qt的两个QList成员变量导致崩溃

c++ - 指针有拷贝构造函数吗?

operator-overloading - Dart ,重载 [] 运算符?

c++ - 努力使 '==' 运算符重载工作 (C++)

c++ - 我怎样才能明智地重载放置运算符 new?

当文件具有导入语句时,Python C api PyImport_importmodule 失败