使用' operator '关键字是什么意思?
What does this use of the `operator` keyword mean?
我在cppreference.com上发现了以下代码(我正在查找explicit
关键字的含义)
struct A
{
A(int) {} // converting constructor
A(int, int) {} // converting constructor (C++11)
operator int() const { return 0; }
};
在结构体定义的第三行有这样一行:operator int() const { return 0; }
我不确定这行是做什么的。哪个操作符被重载了,是int吗?
我看了这里,想自己弄清楚这个问题,但我还是摸不着头脑。
是用户定义的转换操作符
http://en.cppreference.com/w/cpp/language/cast_operatorstruct 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
}
相关文章:
- 这个语法std::class<>{}(arg1, arg2) 在C++中是什么意思?
- 标准 N3337 5.2.10 第 7 条中的C++"类型"是什么意思?
- "类模板示例<int>;"语句对 C++11 是什么意思?
- 线应该是什么意思
- "CID"在AT+HTTPPARA= "CID" ,1中是什么意思
- 表达式"b=(b-x)&x"是什么意思?
- 这个表达是什么意思?
- 此代码验证公式是什么意思?
- 跟踪日志中的T.11803()是什么意思?
- 这个额外的关键字在这个 c++ 类声明中是什么意思?
- * 和 ** 在 C++ 函数声明中是什么意思?
- _T("xyz")是什么意思?
- #define Dbg(fmt,..) (0) 是什么意思? 警告:表达式无效
- 这行代码到底是什么意思?
- 当我们说在执行程序时将操作系统的控制权传递给main()函数时,我们的意思是什么
- 这句话在c++中的意思是什么
- 这个typedef的意思是什么
- 这句话的意思是什么
- 意思是什么
- 这个句法的意思是什么?