sách gpt4 ai đã đi

Toán tử c++ kỳ lạ (toán tử unsigned short())

In lại 作者:太空宇宙 更新时间:2023-11-03 10:44:22 29 4
mua khóa gpt4 Nike

我遇到了一个奇怪的 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++ 标准可以说明这一点吗?

1 Câu trả lời

该函数是用户定义的转换运算符。更多详细信息,请访问 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/

29 4 0
Bài viết được đề xuất: c# - 如何更改花括号的自动格式化定位?
Bài viết được đề xuất: java - c++ - 计算一个类的实例化次数
Bài viết được đề xuất: MySQL 服务器表创建 - "invalid syntax"
Bài viết được đề xuất: c++ - 二叉树的深拷贝
太空宇宙
Hồ sơ cá nhân

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá Didi Taxi miễn phí
Mã giảm giá Didi Taxi
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com