过载"operator X*() const"是什么意思?
What does the overload "operator X*() const" mean?
可能的重复项:
什么是"运算符 T*(void)",何时调用?
正如我们所知,以下代码是重载 * 和 & 运算符
X& operator*() const
{
return *this;
}
X* operator&() const
{
return this;
}
但我不知道下面的代码是什么意思?(它可以通过构建)似乎用来获取 X 的指针。
operator X*() const
{
return this;
}
operator X*() const
{
return this;
}
Implicit conversion operator
键入 X*
。这是用户定义的转换。有关详细信息,请阅读标准12.3
。相关 从 BoostCon 谈话中重载取消引用运算符的奇怪方式
这是一种所谓的用户定义转换或UDC。它们允许您通过构造函数或特殊转换函数指定到其他类型的转换。
语法如下所示:
operator <some_type_here>();
因此,您的特定情况是转换为类型X*
运算符。
在编写这些代码时,您应该记住一些事项:
- UDC 不得模棱两可,否则不会被称为
编译器一次只能使用 UDC 隐式转换单个对象,因此链接隐式转换不起作用:
class A { int x; public: operator int() { return x; }; }; class B { A y; public: operator A() { return y; }; }; int main () { B obj_b; int i = obj_b;//will fail, because it requires two implicit conversions: A->B->int int j = A(obj_b);//will work, because the A->B conversion is explicit, and only B->int is implicit. }
派生类中的转换函数不会隐藏基类中的转换函数,除非它们转换为相同的类型。
通过构造器进行转换时,只能使用默认转换。例如:
class A { A(){} A(int){} } int main() { A obj1 = 15.6;//will work, because float->int is a standart conversion A obj2 = "Hello world!";//will not work, you'll have to define a cunstructor that takes a string. }
您可以在此处、此处或此处找到更多信息。
相关文章:
- 初始化或分配空字符串文字到指向 C 中的 char 的指针或指向 C++ 中 const char 的指针的原因是什么
- 在C++17中,引用const字符串的语义应该是什么
- 在只读(即 const)访问器上执行结构化绑定的最佳实践是什么?
- "char const * name() const _WEBSOCKETPP_NOEXCEPT_TOKEN_ {"剂量是什么意思
- 语法问题:"char [5] const &"是什么意思?
- 'note: 候選人: Volume& Volume::operator=(const Volume&)'.这个错误是什么?
- 在下面函数的返回中添加 const 限定符的重要性是什么?
- int(int)& 或 int(int) const &是什么类型?
- 这个(const vector<vector<int> > &A)"代码段是什么意思?
- classname functionname(const classname & objectname)是什么意思?
- const自动参考绑定到(NULL)指针 - 实际类型是什么
- "const char(&a)[N]"是什么意思?
- "inline operator T*() const"是什么意思?
- 过载"operator X*() const"是什么意思?
- const T& value() const 是什么意思?
- 函数头后面的const是什么意思
- const T*const是什么意思
- 函数声明(虚拟无效打印标记表() const = 0;)中函数名称后"Type Qualifier (const)"是什么意思?
- 在C++重载运算符时"const"是什么意思
- C++:"T const *[]"是什么意思?