重载运算符
Overloading operator
谁能解释一下这个重载运算符是如何调用的?我了解动态转换和条件三元的作用,但我不了解运算符。
头文件:
// ------------------------------------------------------
Class Base
{
public:
Base ();
operator Derived &();
private:
Base * me;
}
//--------------------------------------------------
Class Derived : public Base
{
public:
Derived ()
}
//----------------------------------------------------
inline Base::operator Derived &() {return *(dynamic_cast<Derived *>(me?me:this));}
源文件:
Base::Base()
{
me = new Derived()
}
运算符operator Derived &()
是转换运算符:
12.3.2/1 A member function of a class X having no parameters with a name of the form
conversion-function-id:
operator conversion-type-id
(...)
specifies a conversion from X to the type specified by the
conversion-type-id. Such functions are called conversion functions. No
return type can be specified.
因此它将 Base
对象转换为对 Derived
的引用。
注意:这种结构看起来非常奇怪和危险:它是一种不小心的沮丧。如果您使用此运算符的对象不是 Derived
(例如 "pure" Base
对象或从 Base
派生的另一个 class 但不是来自 Derived
) dynamic_cast
会 return 一个 nullptr
,这会导致 UB:
8.3.2/5: (...) Note: in particular, a null reference cannot exist in a well-defined program, because the only way to create such a
reference would be to bind it to the “object” obtained by indirection
through a null pointer, which causes undefined behavior.
谁能解释一下这个重载运算符是如何调用的?我了解动态转换和条件三元的作用,但我不了解运算符。
头文件:
// ------------------------------------------------------
Class Base
{
public:
Base ();
operator Derived &();
private:
Base * me;
}
//--------------------------------------------------
Class Derived : public Base
{
public:
Derived ()
}
//----------------------------------------------------
inline Base::operator Derived &() {return *(dynamic_cast<Derived *>(me?me:this));}
源文件:
Base::Base()
{
me = new Derived()
}
运算符operator Derived &()
是转换运算符:
12.3.2/1 A member function of a class X having no parameters with a name of the form conversion-function-id: operator conversion-type-id (...)
specifies a conversion from X to the type specified by the conversion-type-id. Such functions are called conversion functions. No return type can be specified.
因此它将 Base
对象转换为对 Derived
的引用。
注意:这种结构看起来非常奇怪和危险:它是一种不小心的沮丧。如果您使用此运算符的对象不是 Derived
(例如 "pure" Base
对象或从 Base
派生的另一个 class 但不是来自 Derived
) dynamic_cast
会 return 一个 nullptr
,这会导致 UB:
8.3.2/5: (...) Note: in particular, a null reference cannot exist in a well-defined program, because the only way to create such a reference would be to bind it to the “object” obtained by indirection through a null pointer, which causes undefined behavior.