gpt4 book ai didi

c++ - 使用 `operator` 关键字是什么意思?

转载 作者:行者123 更新时间:2023-11-30 02:36:38 26 4
gpt4 key购买 nike

我在 cppreference.com 上找到了以下代码(我正在查找 explicit 关键字的含义。)

struct A
{
A(int) {} // converting constructor
A(int, int) {} // converting constructor (C++11)
operator int() const { return 0; }
};

在结构定义的第三行有一行:operator int() const { 返回 0; }

我不确定该行的作用。什么运算符被重载了,是 int 吗?

我看了here尝试自己解决这个问题,但我仍在摸不着头脑。

最佳答案

是用户自定义的转换运算符

http://en.cppreference.com/w/cpp/language/cast_operator

struct X {
//implicit conversion
operator int() const { return 7; }

// explicit conversion
explicit operator int*() const { return nullptr; }

// Error: array operator not allowed in conversion-type-id
// operator int(*)[3]() const { return nullptr; }
using arr_t = int[3];
operator arr_t*() const { return nullptr; } // OK if done through typedef
// operator arr_t () const; // Error: conversion to array not allowed in any case
};

int main()
{
X x;

int n = static_cast<int>(x); // OK: sets n to 7
int m = x; // OK: sets m to 7

int* p = static_cast<int*>(x); // OK: sets p to null
// int* q = x; // Error: no implicit conversion

int (*pa)[3] = x; // OK
}

关于c++ - 使用 `operator` 关键字是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32489679/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com