Is it possible to define the casting operator from one type to another type outside of the class definition as a non-member function? I know it is possible for other operators like operator- but It is not possible with cast operators. For example for two classes A and B, I tried to define the casting operator outside of the A and B scopes as follows:
operator A(const B& b)
{
A a(....);
return a;
}
Explanation: A non-member function can be called inside a member function but the condition is that the non-member function must be declared before the member function. In the above example, the same approach is followed and it becomes possible to invoke a non-member function thus the answer is the factorial of 5 i.e. 120.
Any function declarations are allowed, with additional syntax elements that are only available for non-static member functions: pure-specifiers, cv-qualifiers, ref-qualifiers, final and override specifiers (since C++11), and member initialization lists . 1) For an object of type X using the class member access operator
Non-static member functions. Within the body of a non-static member function of X, any id-expression E (e.g. an identifier) that resolves to a non-type non-static member of X or of a base class of X, is transformed to a member access expression (*this).E (unless it's already a part of a member access expression).
During overload resolution, non-static member function with a cv-qualifier sequence of class X is treated as follows: no ref-qualifier: the implicit object parameter has type lvalue reference to cv-qualified X and is additionally allowed to bind rvalue implied object argument
No, conversion functions must be member functions.
From C++11, [class.conv.fct]/1:
A member function of a class
X
having no parameters with a name of the form [operator
conversion-type-id] specifies a conversion fromX
to the type specified by the conversion-type-id. Such functions are called conversion functions.
There are no other conversion functions, in particular there are no non-member conversion functions.
Conversion operators are specific to class i.e they provide a means to convert your-defined type to some other type. So, they must be the member of a class for which they are serving purpose :-
for e.g:-
class Rational
{
public:
operator double ();
};
Here operator double provide a means to convert Rational object to double.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With